Docker is a set of tools for managing and delivering services or application components as isolated packages called containers. This technology become more popular in present time along with increase in demand of micro-services architecture, continous integration, and faster features or services delivery.
This article shows you how to ship your Node application as Docker image and deploy it as a container.
1. Initiate a Node project.
mkdir my-node-app
cd ./my-node-app
npm init -y
2. Write a sample Node application named server.js
in your project directory.
const http = require('http');
const chalk = require('chalk');
const server = http.createServer(function(req,res){
res.end('Hello from Node server.');
});
server.listen(5000, ()=>{
console.log(chalk.green('Your server is running on port 5000!'));
});
3. Install your Node application dependency.
npm install --save chalk
4. Write a Dockerfile
file in your project directory.
# syntax=docker/dockerfile:1
FROM node:14.17.1
ENV NODE_ENV=production
WORKDIR /app
COPY ["package.json", "package-lock.json", "./"]
RUN npm i --production
COPY . .
CMD ["node", "server.js"]
5. Write a .dockerignore
file in your project directory for ignoring node_modules
directory.
node_modules
6. Build your application as a Docker image.
docker build --tag my-node-app .
7. Specify tag name of your image with version of your application.
docker tag my-node-app:latest my-node-app:v1.0.0
8. Run your application as a container.
docker run -d -p 3000:5000 --name nodeServerApp my-node-app
9. Because you have exposed port 5000 of the container to port 3000 of your host, you can access your app services through http://localhost:3000.
Comments
Post a Comment