0
# Version Control Integration
1
2
PM2 version control integration for managing application deployments with Git. Provides automatic deployment, version navigation, and source code management capabilities for production applications.
3
4
## Capabilities
5
6
### Git Integration and Deployment
7
8
Manage application deployments using Git repositories with automatic pull, restart, and reload operations.
9
10
```javascript { .api }
11
/**
12
* Pull latest changes and restart process
13
* @param process_name - Process name or ID to update
14
* @param callback - Called when pull and restart completes
15
*/
16
function pullAndRestart(process_name: string, callback?: (err: Error, result: any) => void): void;
17
18
/**
19
* Pull latest changes and reload process (zero-downtime)
20
* @param process_name - Process name or ID to update
21
* @param callback - Called when pull and reload completes
22
*/
23
function pullAndReload(process_name: string, callback?: (err: Error, result: any) => void): void;
24
25
/**
26
* Pull specific commit and restart
27
* @param process_name - Process name or ID
28
* @param commit_id - Git commit ID to pull
29
* @param callback - Called when operation completes
30
*/
31
function pullCommitId(process_name: string, commit_id: string, callback?: (err: Error, result: any) => void): void;
32
```
33
34
**Usage Examples:**
35
36
```javascript
37
const pm2 = require('pm2');
38
39
pm2.connect((err) => {
40
if (err) throw err;
41
42
// Pull latest changes and restart
43
pm2.pullAndRestart('my-app', (err, result) => {
44
if (err) throw err;
45
console.log('Application updated and restarted');
46
});
47
48
// Pull latest changes with zero-downtime reload
49
pm2.pullAndReload('my-app', (err, result) => {
50
if (err) throw err;
51
console.log('Application updated with zero downtime');
52
});
53
54
// Pull specific commit
55
pm2.pullCommitId('my-app', 'abc123def456', (err, result) => {
56
if (err) throw err;
57
console.log('Specific commit deployed');
58
});
59
});
60
```
61
62
### Version Navigation
63
64
Navigate through version history with backward and forward operations.
65
66
```javascript { .api }
67
/**
68
* Move to previous version/commit
69
* @param process_name - Process name or ID
70
* @param callback - Called when backward navigation completes
71
*/
72
function backward(process_name: string, callback?: (err: Error, result: any) => void): void;
73
74
/**
75
* Move to next version/commit in history
76
* @param process_name - Process name or ID
77
* @param callback - Called when forward navigation completes
78
*/
79
function forward(process_name: string, callback?: (err: Error, result: any) => void): void;
80
```
81
82
**Usage Examples:**
83
84
```javascript
85
// Rollback to previous version
86
pm2.backward('my-app', (err, result) => {
87
if (err) throw err;
88
console.log('Rolled back to previous version');
89
});
90
91
// Move forward to next version
92
pm2.forward('my-app', (err, result) => {
93
if (err) throw err;
94
console.log('Moved forward to next version');
95
});
96
```
97
98
### Deployment Configuration
99
100
Configure applications for Git-based deployment using ecosystem files.
101
102
```javascript
103
// ecosystem.config.js with deployment configuration
104
module.exports = {
105
apps: [{
106
name: 'my-app',
107
script: 'app.js',
108
env: {
109
NODE_ENV: 'development'
110
},
111
env_production: {
112
NODE_ENV: 'production'
113
}
114
}],
115
116
deploy: {
117
production: {
118
user: 'deploy',
119
host: ['server1.example.com', 'server2.example.com'],
120
ref: 'origin/master',
121
repo: 'git@github.com:username/my-app.git',
122
path: '/var/www/production',
123
'pre-deploy-local': '',
124
'post-deploy': 'npm install && pm2 reload ecosystem.config.js --env production',
125
'pre-setup': '',
126
'post-setup': 'ls -la'
127
},
128
129
staging: {
130
user: 'deploy',
131
host: 'staging.example.com',
132
ref: 'origin/develop',
133
repo: 'git@github.com:username/my-app.git',
134
path: '/var/www/staging',
135
'post-deploy': 'npm install && pm2 restart ecosystem.config.js --env staging'
136
}
137
}
138
};
139
```
140
141
### CLI Deployment Commands
142
143
PM2 provides CLI commands for deployment operations:
144
145
```bash { .api }
146
# Setup deployment environment
147
pm2 deploy ecosystem.config.js production setup
148
149
# Deploy to production
150
pm2 deploy ecosystem.config.js production
151
152
# Deploy specific branch
153
pm2 deploy ecosystem.config.js production --branch feature/new-feature
154
155
# Deploy and update specific process
156
pm2 deploy ecosystem.config.js production update
157
158
# Revert to previous deployment
159
pm2 deploy ecosystem.config.js production revert 1
160
```
161
162
**Deployment Workflow Examples:**
163
164
```bash
165
# Initial setup on remote server
166
pm2 deploy ecosystem.config.js production setup
167
168
# Deploy latest changes
169
pm2 deploy ecosystem.config.js production
170
171
# Deploy specific commit
172
pm2 deploy ecosystem.config.js production --commit abc123
173
174
# Check deployment status
175
pm2 deploy ecosystem.config.js production status
176
177
# Rollback last deployment
178
pm2 deploy ecosystem.config.js production revert 1
179
```
180
181
## Advanced Version Control Features
182
183
### Automatic Deployment with Webhooks
184
185
Set up automatic deployments triggered by Git webhooks:
186
187
```javascript
188
// webhook-handler.js
189
const pm2 = require('pm2');
190
const express = require('express');
191
const app = express();
192
193
app.use(express.json());
194
195
app.post('/webhook/deploy', (req, res) => {
196
const { ref, repository } = req.body;
197
198
// Only deploy on master branch push
199
if (ref === 'refs/heads/master') {
200
pm2.connect((err) => {
201
if (err) {
202
console.error('PM2 connection failed:', err);
203
return res.status(500).json({ error: 'PM2 connection failed' });
204
}
205
206
// Pull latest changes and reload
207
pm2.pullAndReload('my-app', (err, result) => {
208
pm2.disconnect();
209
210
if (err) {
211
console.error('Deployment failed:', err);
212
return res.status(500).json({ error: 'Deployment failed' });
213
}
214
215
console.log('Deployment successful');
216
res.json({ success: true, message: 'Deployment completed' });
217
});
218
});
219
} else {
220
res.json({ message: 'No deployment needed' });
221
}
222
});
223
224
app.listen(3001, () => {
225
console.log('Webhook handler listening on port 3001');
226
});
227
```
228
229
### Version Control with Environment Management
230
231
Manage different environments with version control:
232
233
```javascript
234
// Multi-environment deployment
235
const deployEnvironment = (env, branch) => {
236
pm2.connect((err) => {
237
if (err) throw err;
238
239
console.log(`Deploying ${env} environment from ${branch} branch`);
240
241
// Use different processes for different environments
242
const processName = `my-app-${env}`;
243
244
pm2.pullAndReload(processName, (err, result) => {
245
pm2.disconnect();
246
247
if (err) {
248
console.error(`${env} deployment failed:`, err);
249
return;
250
}
251
252
console.log(`${env} deployment successful`);
253
});
254
});
255
};
256
257
// Deploy staging from develop branch
258
deployEnvironment('staging', 'develop');
259
260
// Deploy production from master branch
261
deployEnvironment('production', 'master');
262
```
263
264
### Monitoring Deployment Status
265
266
Track deployment history and status:
267
268
```javascript
269
const pm2 = require('pm2');
270
271
// Get deployment information
272
pm2.connect((err) => {
273
if (err) throw err;
274
275
pm2.describe('my-app', (err, description) => {
276
if (err) throw err;
277
278
const proc = description[0];
279
if (proc && proc.pm2_env.versioning) {
280
console.log('Version Information:');
281
console.log('- Repository:', proc.pm2_env.versioning.repo_path);
282
console.log('- Branch:', proc.pm2_env.versioning.branch);
283
console.log('- Commit:', proc.pm2_env.versioning.revision);
284
console.log('- Comment:', proc.pm2_env.versioning.comment);
285
console.log('- Update Date:', new Date(proc.pm2_env.versioning.update_time));
286
}
287
288
pm2.disconnect();
289
});
290
});
291
```
292
293
## Deployment Best Practices
294
295
### 1. Environment Separation
296
297
```javascript
298
module.exports = {
299
apps: [{
300
name: 'app-prod',
301
script: 'app.js',
302
env_production: {
303
NODE_ENV: 'production',
304
PORT: 3000
305
}
306
}, {
307
name: 'app-staging',
308
script: 'app.js',
309
env_staging: {
310
NODE_ENV: 'staging',
311
PORT: 3001
312
}
313
}],
314
315
deploy: {
316
production: {
317
// Production deployment config
318
user: 'deploy',
319
host: 'prod-server.com',
320
ref: 'origin/master',
321
repo: 'git@github.com:user/app.git',
322
path: '/var/www/production'
323
},
324
325
staging: {
326
// Staging deployment config
327
user: 'deploy',
328
host: 'staging-server.com',
329
ref: 'origin/develop',
330
repo: 'git@github.com:user/app.git',
331
path: '/var/www/staging'
332
}
333
}
334
};
335
```
336
337
### 2. Automated Testing in Deployment
338
339
```javascript
340
module.exports = {
341
deploy: {
342
production: {
343
user: 'deploy',
344
host: 'server.com',
345
ref: 'origin/master',
346
repo: 'git@github.com:user/app.git',
347
path: '/var/www/production',
348
'pre-deploy': 'git fetch origin master',
349
'post-deploy': [
350
'npm install',
351
'npm run build',
352
'npm test',
353
'pm2 reload ecosystem.config.js --env production'
354
].join(' && ')
355
}
356
}
357
};
358
```
359
360
### 3. Rollback Strategy
361
362
```bash
363
# Quick rollback commands
364
pm2 deploy ecosystem.config.js production revert 1 # Rollback 1 deployment
365
pm2 deploy ecosystem.config.js production revert 2 # Rollback 2 deployments
366
367
# Using version control API
368
pm2.backward('my-app', (err) => {
369
if (err) throw err;
370
console.log('Rolled back successfully');
371
});
372
```
373
374
## Core Types
375
376
```javascript { .api }
377
interface DeploymentConfig {
378
/** SSH user for deployment */
379
user: string;
380
/** Target host(s) for deployment */
381
host: string | string[];
382
/** Git reference to deploy (branch/tag) */
383
ref: string;
384
/** Git repository URL */
385
repo: string;
386
/** Deployment path on remote server */
387
path: string;
388
/** Commands to run before deployment */
389
'pre-deploy'?: string;
390
/** Commands to run after deployment */
391
'post-deploy'?: string;
392
/** Commands to run during initial setup */
393
'pre-setup'?: string;
394
/** Commands to run after initial setup */
395
'post-setup'?: string;
396
}
397
398
interface VersionInfo {
399
/** Repository path */
400
repo_path?: string;
401
/** Current branch */
402
branch?: string;
403
/** Current commit hash */
404
revision?: string;
405
/** Commit message */
406
comment?: string;
407
/** Last update timestamp */
408
update_time?: number;
409
}
410
```