Lately, as a move towards efficient continuous integration and continuous development( CI/CD ), I have been dockerizing all my applications and running these applications inside containers using Docker
. NodeJS turned out to be a hard nut to crack...but alas it's finally cracked. This is how i managed to dockerize and run a NodeJS RESTFUL app at long last.
Navigate to your preferred file system and create a directory and then change into the created directory.
$ mkdir <foldername> && cd <foldername>
Create a new nodejs app using
npm
oryarn
by running:
$ npm init <application name>
Add your app dependencies such as Express:
$ npm install express --save
You should now have a
package.json
file, thenode_modules
folders and maybe some lock files. Create the main file this command under your app directory terminal window / shell by running:$ touch <filename>.js
5.Edit thepackage.json
file. Add this if not existent under the scripts defintion and save the file.
"scripts": {
"start": "node <mainfile>"
}
- To dockerize the app; add the following files from the terminal under the app directory file system.
$ touch Dockerfile
$ touch docker-compose.yml
- Open and Edit the Dockerfile with the following contents.
# obtain the node image
FROM node
# change to the working directory
WORKDIR <directory_name>
#move the package file to the current working directory
COPY package*.json ./
# install the depedencies
RUN npm install
COPY . .
# run the app
CMD [ "node", <mainfile> ]
- Make a new directory inside the app folder to handle the nginx configuration, cd into the folder and create a new nginx conf file.
mkdir nginx && cd nginx && touch default.conf
- Edit the default conf file with these contents;
environment name
andport
should be obtained and defined in thedocker-compose.yml
file.
http {
upstream backend {
server <environment_name: port>
}
server {
location / {
proxy_pass http://backend;
}
}
}
- Edit the
docker-compose.yml
with these contents.
versions: '3',
services:
nginx_server:
image: nginx #image of the nginx
volumes:
- './nginx/default.conf:/etc/nginx/nginx.conf'
ports:
- '8000:80'
#define the node app container
app:
container_name: <container name>
build:
context: .
dockerfile: Dockerfile #name of the dockerfile we created
ports:
- '3000:80' #docker container port = 3000, host port= 80
environment:
- APPID=3000
Top comments (0)