Dockerizing Node App
Docker allows to package an application referred as Images and run its instance Container. Container offers light-weight process, an alternative to Virtual Machine.
Prerequisites
- NodeJS
- ExpressJS
Create NodeJS App
Firstly, create a folder app and make it working directory. Use npm init command to create package.json.
$ mkdir app
$ cd app
$ npm init --yInstall express package in app directory.
$ npm i expressNext, create index.js file in app directory and write down server code.
In terminal, you can start application and browse http://localhost:3000.
$ node .Create Docker
Download and Install Docker (Download)
Next, create Dockerfile and open it in Editor.
Get Harish Maryada’s stories in your inbox
Join Medium for free to get updates from this writer.
First things first, define from which node image we need to build our app image. Pick a latest version from Docker Hub
# DockerfileFROM node:14
Next create working directory of image, complete app code will be holded by this directory
# create app working directoryWORKDIR /usr/app
Copy package.json and package-lock.json as it is from our app directory to docker image app directory, then install all application dependency packages.
# Copy package.json and package-lock.jsonCOPY package*.json ./# install app dependencies
RUN npm install
Copy source code from working app directory to docker image app directory. Expose on a port on which application has to run.
# Copy code
COPY . .# Export port
EXPOSE 8080# Start server
CMD [ "node", "index.js" ]
Your complete Dockerfile looks like
Copy code will also copy node modules which can be ignored by defining docker ignore file. Create a file .dockerignore and copy the below code to exclude node packages and logs
node_modules
npm-debug.logBuild app image
In your working directory, build image by running the command( docker build -t <app-name> .).
$ docker build -t node/app .Congrats, docker image is created and ready for deployment ! To verify images exists in list of docker images run
$ docker images# Example
REPOSITORY TAG ID CREATED
node 12 1734b2b838d1 2 minute ago
node/app latest d24d3545b3d7 1 minute ago
Run node/app image
Run application in detach mode(-d) on port (-p)of choice. Server is up and running on specified port.
docker run -p 49160:3000 -d node/appContainer is created and view list of container using,
$ docker psFinally, browse http://localhost:49160 to verify the docker is running as earlier.
References :
That ‘s all!
Application is containerized and ready for deployment. Happy coding and good luck!










