Dockerize NodeJS with MongoDB

Victor Yeo
1 min readJul 8, 2020

--

Firstly, we create a NodeJS application. It is available at this link.

Secondly, we create a Dockerfile for the NodeJS application.

FROM node:11.1.0-alpineRUN mkdir -p /usr/local/victor
WORKDIR /usr/local/victor
RUN apk — update add git
RUN git clone -b master https://github.com/victoryeo/tinycoinv2.git
WORKDIR /usr/local/victor/tinycoinv2
RUN npm install
EXPOSE 4040ENTRYPOINT [“npm”]
CMD [“start”]

In the Dockerfile, apk is the command use in Alpine Linux to update the available packages.

Thirdly, we use a docker-compose.yml file to create two containers.

version: “3” 
services:
app:
container_name: tinycoin
restart: always
build: .
ports:
— “4040:8000”
links:
— mongo
mongo:
container_name: mongo
image: mongo
ports:
— “27018:27017”

The ports in docker compose file, expose the internal port 4040 to external port number 8000.

Run the “docker-compose build” to build the container images.

If you make changes to NodeJs file, run “docker-compose build — no-cache”, to tell docker not using cache when building the image.

To remove docker images, use the command:

docker rm <name>

Run “docker-compose up” to start docker container.

In the messages shown on the terminal, if you see the error:

Error: unable to connect to database:mongodb://localhost:27017/tiny-coin

Instead of using localhost, use the service name “mongo” given to the mongo service in docker-compose.yml

mongodb://mongo:27017/tiny-coin

To test connecting to mongodb container, in another terminal, run the mongodb client command:

mongo mongodb://localhost:27018/tiny-coin

Notice, within containers, we use the port number 27017. Outside the containers, we use the port number 27018.

--

--

No responses yet