Docker has emerged to be a standard of building and deploying applications. The best part of docker is it gives a complete abstraction over the environment or OS. There are plenty of material on what docker is, or how it works, however, what we are going to discuss over here is to how to put your nodeJS express app in docker container.
What we need
- A computer with docker installed on it. Preferably linux/mac.
Windows has its challenges to run docker desktop, especially win10 Home editions, so you need to really go through the documentation in docker site before installing docker.
WSL too is dependent on Win10, so go as per the documentation given in docker website.
- A Express Application to play with.
I have an express app, created out of express generator hosted on github which i'm going to be using for this exercise.
The code on this repo runs on PORT 4000, and exposes API
http://localhost:4000/card-deck/shuffle. This repo makes a call to external APIs, so your system should be enabled to make API calls.
If you are using my repository, don't run npm install. :-O. Lets not waste time here running a simple express app, lets just go straight into using docker.
Within the repository, create a
Dockerfile, and a
.dockerignore file, next to package.json
touch Dockerfile touch .dockerignore
Lets open Dockerfile and add these entries into it.
FROM node:12-slim # create a directory in your docker image WORKDIR /app # install dependencies COPY ./package*.json ./ # run npm install. you just need the runtime dependencies here RUN npm ci --only-production # Copy the rest of the code COPY ./ ./ # Expose the port, on which your application is running EXPOSE 4000 # Run the code CMD [ "node", "./bin/www" ]
Save this Dockerfile.
As you would have guessed already, .dockerignore contains the entries which will be ignored when you're copying all your code on the docker image. Enter the following in the .dockerignore file and save it.
Build your first docker image
docker build -t card-deck-test .
Check the image in your local registry
It should give you an output like
REPOSITORY TAG IMAGE ID card-deck-test latest aaaa1111dddd1111
docker run -p 4000:4000 -d card-deck-test
The express application is now running on port 4000 in the container, and the container is exposing port 4000. So to summarise, you can now see your application running by opening
http://localhost:4000/card-deck/shuffle on your browser.
Play around with docker
- Run multiple containers simultaneously
docker run -p 4000:4000 -d card-deck-test docker run -p 4001:4000 -d card-deck-test docker run -p 4002:4000 -d card-deck-test
- See the containers running
docker ps -a
- Stop the docker container
docker stop [CONTAINER_ID]
- Remove the docker container
docker rm [CONTAINER_ID]