auto-deploy-sh 2.0.1 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,121 +1,128 @@
1
- # Auto-deploy-sh
2
-
3
- English|[简体中文](README_zh_CN.md)
4
-
5
- This project aims to lower deployment barriers by providing an ultra-simple configuration and minimal dependency automated Docker deployment workflow. It helps developers quickly deploy applications to cloud servers without complex environment setups.
6
-
7
- ## Deployment Commands
8
-
9
- ### Project-Specific Configuration
10
-
11
- **Install:**
12
-
13
- ```bash
14
- npm install auto-deploy-sh -D
15
- ```
16
-
17
- **Run:**
18
-
19
- - Add to `package.json`:
20
-
21
- ```json
22
- "scripts": {
23
- "deploy": "auto-deploy-sh"
24
- }
25
- ```
26
-
27
- 2. Execute in terminal:
28
-
29
- ```bash
30
- npm run deploy
31
- ```
32
-
33
- ### Global Configuration
34
-
35
- **Install:**
36
-
37
- ```bash
38
- npm install auto-deploy-sh -g
39
- ```
40
-
41
- **Run** (in the root directory of the project to deploy):
42
-
43
- ```bash
44
- auto-deploy-sh
45
- ```
46
-
47
- ### Advanced Usage
48
-
49
- Run with a **custom configuration file**:
50
-
51
- ```bash
52
- auto-deploy <config-path>
53
- # OR
54
- auto-deploy -f <config-path>
55
- ```
56
-
57
- Useful for multi-environment deployment (e.g., development, staging, production).
58
-
59
- ## Configuration File Reference
60
-
61
- The configuration file is **fixed as `deploy-config.json`**. If missing, the tool will **guide you to create it** (stored in the command execution directory by default) and automatically add `deploy-config.json` to `.gitignore` to **prevent accidental commits of sensitive data**.
62
-
63
- > ⚠️ **Critical Note**: The configuration file contains sensitive information (e.g., passwords). If creating manually, ensure `deploy-config.json` is added to `.gitignore`.
64
-
65
- ### Configuration Properties
66
-
67
- - `host`: Remote server IP address or domain name.
68
- - `port`: SSH port number.
69
- - `user`: SSH username for the remote server.
70
- - `password`: Password for the SSH user.
71
- - `beforLaunch`: **Pre-deployment commands** (array of strings) to execute locally before starting the deployment (e.g., `["npm run build"]`).
72
- - `Dockerfile`: **Optional**. If omitted: 1. Check `dockerBuildFiles` for a file named `Dockerfile`; 2. If not found, search for `Dockerfile` in the **first-level directory of the current execution environment**.
73
- - `dockerBuildFiles`: Files/directories to include in the Docker build context (required for Dockerfile execution).
74
- - `imageTag`: Docker image tag, formatted as `[registry-url/][username/project-name]:[tag]` (e.g., `my-registry.com/user/my-app:v1.0`).
75
- - `containerName`: Unique name for the running container (ensures no conflicts with existing containers).
76
- - `BindPorts`: Port mapping, formatted as `<host-port>:<container-port>` (e.g., `"8080:80"`).
77
- - `Options`: **Optional** advanced settings (all sub-properties are optional)
78
- - `volumes`: Volume mappings (array of strings), formatted as `[host-path/volume-name]:[container-path]:[optional-flags]` (e.g., `["/host/data:/container/data:ro"]`).
79
- - `networks`: Connect the container to a custom Docker network (created via `docker network create <network-name>`) for inter-container communication.
80
-
81
- ### Format Introduction
82
-
83
- ```json
84
- {
85
- "host": "string",
86
- "port": "number | string",
87
- "user": "string",
88
- "password": "string",
89
- "beforLaunch": "string[]",
90
- "Dockerfile": "string",
91
- "dockerBuildFiles": "string[]",
92
- "imageTag": "string",
93
- "containerName": "string",
94
- "BindPorts": "string",
95
- "Options": {
96
- "volumes": "string[]",
97
- "networks": "string"
98
- }
99
- }
100
- ```
101
-
102
- ### Full Configuration Example
103
-
104
- ```json
105
- {
106
- "host": "your-server-ip",
107
- "port": 22,
108
- "user": "ssh-username",
109
- "password": "ssh-password",
110
- "beforLaunch": ["npm run build"],
111
- "Dockerfile": "./Dockerfile",
112
- "dockerBuildFiles": ["./dist", "./package.json"],
113
- "imageTag": "my-app:latest",
114
- "containerName": "my-app-container",
115
- "BindPorts": "80:80",
116
- "Options": {
117
- "volumes": ["/host/logs:/app/logs:rw"],
118
- "networks": "my-custom-network"
119
- }
120
- }
121
- ```
1
+ # Auto-deploy-sh
2
+
3
+ English|[简体中文](README_zh_CN.md)
4
+
5
+ This project aims to lower deployment barriers by providing an ultra-simple configuration and minimal dependency automated Docker deployment workflow. It helps developers quickly deploy applications to cloud servers without complex environment setups.
6
+
7
+ ## Deployment Commands
8
+
9
+ ### Project-Specific Configuration
10
+
11
+ **Install:**
12
+
13
+ ```bash
14
+ npm install auto-deploy-sh -D
15
+ ```
16
+
17
+ **Run:**
18
+
19
+ - Add to `package.json`:
20
+
21
+ ```json
22
+ "scripts": {
23
+ "deploy": "auto-deploy-sh"
24
+ }
25
+ ```
26
+
27
+ 2. Execute in terminal:
28
+
29
+ ```bash
30
+ npm run deploy
31
+ ```
32
+
33
+ ### Global Configuration
34
+
35
+ **Install:**
36
+
37
+ ```bash
38
+ npm install auto-deploy-sh -g
39
+ ```
40
+
41
+ **Run** (in the root directory of the project to deploy):
42
+
43
+ ```bash
44
+ auto-deploy-sh
45
+ ```
46
+
47
+ ### Advanced Usage
48
+
49
+ Run with a **custom configuration file**:
50
+
51
+ ```bash
52
+ auto-deploy-sh <config-path>
53
+ # OR
54
+ auto-deploy-sh -f <config-path>
55
+ ```
56
+
57
+ Useful for multi-environment deployment (e.g., development, staging, production).
58
+
59
+ ## Configuration File Reference
60
+
61
+ The configuration file is **fixed as `deploy-config.json`**. If missing, the tool will **guide you to create it** (stored in the command execution directory by default) and automatically add `deploy-config.json` to `.gitignore` to **prevent accidental commits of sensitive data**.
62
+
63
+ > ⚠️ **Critical Note**: The configuration file contains sensitive information (e.g., passwords). If creating manually, ensure `deploy-config.json` is added to `.gitignore`.
64
+
65
+ ### Configuration Properties
66
+
67
+ - `host`: Remote server IP address or domain name.
68
+ - `port`: SSH port number.
69
+ - `user`: SSH username for the remote server.
70
+ - `password`: Password for the SSH user.
71
+ - `beforLaunch`: **Pre-deployment commands** (array of strings) to execute locally before starting the deployment (e.g., `["npm run build"]`).
72
+ - `Dockerfile`: **Optional**. If omitted: 1. Check `dockerBuildFiles` for a file named `Dockerfile`; 2. If not found, search for `Dockerfile` in the **first-level directory of the current execution environment**.
73
+ - `dockerBuildFiles`: Files/directories to include in the Docker build context (required for Dockerfile execution).
74
+ - `imageTag`: Docker image tag, formatted as `[registry-url/][username/project-name]:[tag]` (e.g., `my-registry.com/user/my-app:v1.0`).
75
+ - `containerName`: Unique name for the running container (ensures no conflicts with existing containers).
76
+ - `BindPorts`: Port mapping, formatted as `<host-port>:<container-port>` (e.g., `"8080:80"`).
77
+ - `restart` (optional): Container restart policy, controls how Docker handles container restarts. The following options are supported:
78
+ - `no`(default): The container **will not restart automatically after it exits**. It will also remain stopped after Docker or system restarts. Suitable for one-off tasks or debugging scenarios.
79
+ - `always`: The container **will always restart automatically** if it stops. It will also start automatically after Docker or system restarts.Even if the container is manually stopped, it will be restarted again after Docker restarts.
80
+ - `unless-stopped`(recommended): The container will automatically restart on failure and start after Docker or system restarts.**If the container is manually stopped, it will not be restarted again**, making it suitable for long-running production services.
81
+ - `on-failure`: The container **will restart only if it exits with a non-zero status code**. It will not restart on normal exits (exit code 0).
82
+ - `Options`: **Optional** advanced settings (all sub-properties are optional)
83
+ - `volumes`: Volume mappings (array of strings), formatted as `[host-path/volume-name]:[container-path]:[optional-flags]` (e.g., `["/host/data:/container/data:ro"]`).
84
+ - `networks`: Connect the container to a custom Docker network (created via `docker network create <network-name>`) for inter-container communication.
85
+
86
+ ### Format Introduction
87
+
88
+ ```json
89
+ {
90
+ "host": "string",
91
+ "port": "number | string",
92
+ "user": "string",
93
+ "password": "string",
94
+ "beforLaunch": "string[]",
95
+ "Dockerfile": "string",
96
+ "dockerBuildFiles": "string[]",
97
+ "imageTag": "string",
98
+ "containerName": "string",
99
+ "BindPorts": "string",
100
+ "restart": "'no' | 'always' | 'unless-stopped' | 'on-failure'",
101
+ "Options": {
102
+ "volumes": "string[]",
103
+ "networks": "string[]"
104
+ }
105
+ }
106
+ ```
107
+
108
+ ### Full Configuration Example
109
+
110
+ ```json
111
+ {
112
+ "host": "your-server-ip",
113
+ "port": 22,
114
+ "user": "ssh-username",
115
+ "password": "ssh-password",
116
+ "beforLaunch": ["npm run build"],
117
+ "Dockerfile": "./Dockerfile",
118
+ "dockerBuildFiles": ["./dist", "./package.json"],
119
+ "imageTag": "my-app:latest",
120
+ "containerName": "my-app-container",
121
+ "BindPorts": "80:80",
122
+ "restart": "unless-stopped",
123
+ "Options": {
124
+ "volumes": ["/host/logs:/app/logs:rw"],
125
+ "networks": ["my-custom-network", "my-custom-network-1"]
126
+ }
127
+ }
128
+ ```
@@ -43,6 +43,32 @@ const configMethod = {
43
43
  type: 'input',
44
44
  message: 'Bind Ports(such as 8080:8080): ',
45
45
  },
46
+ restart: {
47
+ type: 'select',
48
+ message: 'Container restart policy (when should Docker restart this container?)',
49
+ choices: [
50
+ {
51
+ name: 'no (default)',
52
+ value: 'no',
53
+ description: 'Never restart. Container stays stopped even after Docker or system restarts.',
54
+ },
55
+ {
56
+ name: 'always',
57
+ value: 'always',
58
+ description: 'Always restart if it stops. Will also start automatically after Docker or system reboot.',
59
+ },
60
+ {
61
+ name: 'unless-stopped (recommended)',
62
+ value: 'unless-stopped',
63
+ description: 'Restart automatically unless you manually stop it. Will NOT restart again if stopped by user.',
64
+ },
65
+ {
66
+ name: 'on-failure',
67
+ value: 'on-failure',
68
+ description: 'Restart only on non-zero exit code. Useful for jobs or scripts that may fail.',
69
+ },
70
+ ],
71
+ },
46
72
  };
47
73
  const optionsMethod = {
48
74
  volumes: {
@@ -52,7 +78,8 @@ const optionsMethod = {
52
78
  },
53
79
  networks: {
54
80
  type: 'input',
55
- message: 'Bound network: ',
81
+ message: 'Bound networks (separated by , ): ',
82
+ handleFn: (value) => value.split(','),
56
83
  },
57
84
  };
58
85
  export async function createConfig(rootPath) {
@@ -29,5 +29,6 @@ export declare class Deploy {
29
29
  dockcerImageBuild(ssh: NodeSSH): Promise<void>;
30
30
  buildDocker(ssh: NodeSSH, IMAGE_TAG: string, REMOTEAPPPATH: string, TARGET_DIR: string, CONTAINER_NAME: string): Promise<void>;
31
31
  runDocker(ssh: NodeSSH, CONTAINER_NAME: string): Promise<void>;
32
+ judgeNetwork(ssh: NodeSSH, networks: string[]): Promise<void>;
32
33
  clear(ssh: NodeSSH): Promise<void>;
33
34
  }
@@ -1,4 +1,4 @@
1
- import { log, ora, run, fs, exit, chalk } from "./utils/index.js";
1
+ import { log, ora, run, fs, exit, chalk, inquirer } from "./utils/index.js";
2
2
  import path from 'path';
3
3
  import archiver from 'archiver';
4
4
  export class Deploy {
@@ -186,6 +186,10 @@ export class Deploy {
186
186
  const REMOTE_PATH = this.remotePath;
187
187
  const IMAGE_TAG = this.config.imageTag;
188
188
  const TARGET_DIR = `./${CONTAINER_NAME}`;
189
+ const networks = this.config.Options?.networks || [];
190
+ if (networks.length > 0) {
191
+ await this.judgeNetwork(ssh, networks);
192
+ }
189
193
  await this.execCommand(ssh, {
190
194
  startMsg: 'Start decompress project....',
191
195
  succMsg: 'Decompress project completed.',
@@ -235,6 +239,9 @@ export class Deploy {
235
239
  }
236
240
  async runDocker(ssh, CONTAINER_NAME) {
237
241
  let optionsCLI = `--name ${CONTAINER_NAME} -p ${this.config.BindPorts}`;
242
+ if (this.config.restart) {
243
+ optionsCLI += ` --restart ${this.config.restart}`;
244
+ }
238
245
  const options = this.config.Options;
239
246
  if (options) {
240
247
  const optionsKeys = Object.keys(options);
@@ -248,7 +255,14 @@ export class Deploy {
248
255
  break;
249
256
  }
250
257
  case 'networks': {
251
- optionsCLI += ` --network ${options.networks}`;
258
+ let cli = '';
259
+ if (Array.isArray(options.networks)) {
260
+ cli = options.networks.map((network) => `--network ${network}`).join(' ');
261
+ }
262
+ else {
263
+ cli = `--network ${options.networks}`;
264
+ }
265
+ optionsCLI += ` ${cli}`;
252
266
  break;
253
267
  }
254
268
  default:
@@ -265,6 +279,35 @@ export class Deploy {
265
279
  docker run -d ${optionsCLI}
266
280
  `);
267
281
  }
282
+ async judgeNetwork(ssh, networks) {
283
+ const { stderr, code, stdout } = await ssh.execCommand(`docker network ls --format '{{.Name}}'`);
284
+ if (code !== 0 || (stderr && code !== 0)) {
285
+ stderr && log.error(stderr);
286
+ throw new Error();
287
+ }
288
+ const existNetworks = new Set(stdout
289
+ .split('\n')
290
+ .map(item => item.trim())
291
+ .filter(Boolean));
292
+ const missingNetworks = networks.filter(network => !existNetworks.has(network));
293
+ if (missingNetworks.length > 0) {
294
+ const answer = await inquirer.invoke({
295
+ type: 'confirm',
296
+ message: `The following Docker networks do not exist:\n${JSON.stringify(missingNetworks)}\nDo you want to create them now?`,
297
+ });
298
+ if (answer) {
299
+ let cli = missingNetworks.map(name => `docker network create ${name}`).join(' && ');
300
+ await this.execCommand(ssh, {
301
+ startMsg: `Creating missing Docker networks...`,
302
+ succMsg: `Missing Docker networks created successfully.`,
303
+ }, cli);
304
+ }
305
+ else {
306
+ log.error('Deployment aborted due to missing Docker networks.');
307
+ throw new Error();
308
+ }
309
+ }
310
+ }
268
311
  async clear(ssh) {
269
312
  await ssh.execCommand(`rm -f ${this.remotePath}`);
270
313
  await ssh.execCommand(`rm -rf ${this.REMOTEAPPPATH}/${this.config.containerName}`);
@@ -10,9 +10,10 @@ export type sshConfig = {
10
10
  imageTag: string;
11
11
  containerName: string;
12
12
  BindPorts: string;
13
+ restart?: 'no' | 'always' | 'on-failure' | 'unless-stopped';
13
14
  Options: {
14
15
  volumes: string[];
15
- networks: string;
16
+ networks: string[];
16
17
  };
17
18
  };
18
19
  export type fileData = string | NodeJS.ArrayBufferView;
@@ -31,7 +31,7 @@ export class inquirer {
31
31
  break;
32
32
  case 'confirm':
33
33
  args.theme = {
34
- prefix: chalk.warn(''),
34
+ prefix: chalk.warn('?'),
35
35
  style: {
36
36
  answer: (text) => chalk.done(text),
37
37
  error: (text) => chalk.error(text),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "auto-deploy-sh",
3
- "version": "2.0.1",
3
+ "version": "2.1.0",
4
4
  "description": "Automated Docker deployment tool",
5
5
  "bin": {
6
6
  "auto-deploy-sh": "./dist/cli/index.js"