Deploy NodeJs API using docker
Before we get to this tutorial, you need a basic setup of nodejs and mongodb application. If you don't have any setup, please refer to the NodeJS authentication with Passport, JWT and MongoDB Part1 for reference.
First thing you need to do is install docker desktop. Docker provides a pretty documentation to install and run docker in your machine. Please follow the link given below to install docker engine and docker compose in your local environment.
- Windows users: You can use the instructions given in the link to download docker desktop and install it on your windows machine. Both docker engine and docker compose comes with this installation.
- Mac users: Follow the link to download docker desktop and install it on your MacOS. Both docker engine and docker compse comes with this installation.
- Linux - Ubuntu: Follow this link to install docker engine. And follow this link to install docker compose
The dockerfile contains the instructions on how your project must be built inside its containers.
Create a new file with the name
Dockerfile inside the root directory of your project and add the following code to it.
// Dockerfile FROM node:12 WORKDIR /usr/src/app COPY package*.json ./ RUN npm install COPY . . EXPOSE 8001 CMD [ "npm", "run", "start" ]
Behind the scenes these are the instructions we are giving docker.
- Docker downloads a base image containing nodejs version 12.
- Docker sets its working directory under
usr/src/appinside the container.
- Docker copies the
package.jsonfile from our local project directory to
appdirectories root folder.
- Docker then runs
npm installin the root directory and installs required
- Docker then copies all the files under the project into
- Docker then exposes port 8001 to the host machine.
- It sets the execution command to be
npm run start
The docker-compose file helps in bringing up multiple containers together using one command. In this file, one can add details regarding different services the project depends on such as Databases, Logging tools, etc.
docker-compose.yml file at the root of your project.
// docker-compose.yml version: '3.8' services: api: build: context: . ports: - '8001:8001' depends_on: - mongo mongo: image: mongo ports: - '27017:27017'
This file has listed mongodb as one of the dependencies for the project.
.env file and add the DB_URL parameter value equivalent to dockers internal IP address
Now that all the files are added, run the following command to build the docker image:
This should bring your application up and run it on port 8001. Congratulations, you have successfully added built and deployed your app using docker. If you had any difficulties in following this tutorial, please refer to my GitHub repository: https://github.com/AparnaJoshi007/nodejs-authentication-api/