Recently in the deployment of node. JS program, wrote a simple script, found quite simple, can't help but want to share with you.
Configuration file
First, the database connection for the local test environment and the production environment These configuration information is not the same, you need to separate it into a directory of two files config
, such as:
Development environment configuration file config/development.js
:
module.exports = { port: 3001, mysql: { user: ‘root‘ }};
Production environment configuration file config/production.js
:
module.exports = { port: 80, mysql: { user: ‘myapp‘, password: ‘2zbonsjzl305vkh3‘ }};
Also set up a program to automatically load the corresponding environment configuration, files config/index.js
:
VarPath= Require(' Path ');Set environment variables by NODE_ENV, default to production if not specifiedVarEnv=Process.Env.Node_env|| ' Production ';Env=Env.toLowerCase();Loading configuration filesVarFile=Path.Resolve(__dirname,Env);Try { VarConfig= Module.Exports= Require(File);Consolelog ( Env, File); } catch ( Err { Console.error ( Env, File); throw Err; /span>
Assuming that the application's portal file is app.js
, you can load the configuration in the following ways:
var config = require(‘./config‘);console.log(‘listen on port %s‘, config.port);// 如果是开发环境,将输出 listen on port 3001// 如果是生产环境,将输出 listen on port 80
Local Development testing
For convenience, I create a new script file run
with the following code:
export NODE_ENV=developmentnode app
To start the program, execute it directly at the command line ./run
.
Deploying Apps
Create a new deployment script file deploy
with the following code:
git reset --hardgit pull origin HEADnpm installpm2 stop myapp -fpm2 start app.js -n myapp
This code will automatically pull the latest commit code from the GIT repository and use NPM to install the modules listed in Package.json, and then start by stopping the previously launched application instance.
In order to facilitate the transfer of code to the server side, you need to submit the program code to a private git repository, the first time on a server-side deployment, the code must first clone to the server side, such as:
git clone git[@github](/user/github).com:leizongmin/node-uc-server.git ~/myapp
The app uses pm2
tools to manage processes on the server side, so you'll need to install the tool on the server first:
npm install pm2 -g
Once you have completed the above preparations, we can deploy
implement the automatic Update code by script:
- Commit local modifications to a remote git repository
- Log in to the server and enter the
~/myapp
directory
- Perform
./deploy
The above program executes the environment for Linux, if the development environment is windows, you need to change the file to the run
following code:
set NODE_ENV=developmentnode app
A simple production environment deploying the node. JS Program method