Developing with Docker - NodeJS

Developing with Docker - NodeJS

ยท

3 min read

Steps to Dockerizing a nodejs application

1. Create your nodejs application

In this article, we will use a simple node application: node app

2. Create a dockerfile at the root folder of your application and copy the commands below

#dockerfile 
FROM node:alpine
WORKDIR /usr/app
COPY package.json .
RUN yarn install
COPY . .
CMD ["yarn", "start"]

Let's describe what the commands in the dockerfile do..

#specifies which image and version to pull from docker hub
From node:alpine
#create the app directory inside the Docker image
WORKDIR /usr/app
#copy and install applications dependencies from the package.json 
#into the root of the directory app directory created above.
COPY package.json .
RUN yarn install
#copies your application files into the docker image
COPY . .
#specifies the command to run within the container
CMD ["yarn", "start"]

3. Build your application into an image using the docker file

To build a docker image you need to execute the following command

#docker build โ€“t [name-of-the-image] [dockerfile location]
#the -t flag helps you assign a name to your image
# the period (.) specifies the location of my dockerfile
docker build -t my-first-image .

image.png Run the command docker imagesto check if the image has been created

image.png

ps: ensure docker engine is running on your machine

4. Run the container from the image you build above

The following commands are used to run a container.

docker run --name [name-of-the-container] -p [bind the host port to container's port] [the image you want to run your container from]

docker run  --name my-first-container -p 4000:4000  my-first-image

# The --name flag helps you assign a name to your container
# -p flag helps you expose the container's port to the host(your machine) port

image.png Run the command docker psto check if your container is running

image.png

#a list of files/folders you don't want copied into  your docker image 
#dockerignorefile
node_modules
dockerfile

Main Docker Commands

  1. docker ps - shows a list of all running containers
  2. docker images - shows all images in your machine
  3. docker rm - removes one or more containers
  4. docker rmi - removes one or more images
  5. docker stops- stops one or more running containers
  6. docker kill - kills one or more running containers without a cleanup process
  7. docker exec -it [container id] bash - allows you to access the container's bash/command line

windows : winpty docker exec -it a4c426a7f103} sh

Linux: docker exec -it [container-id] bash

image.png

Great work!!๐ŸŽ‰, you just Dockerized your Nodejs Application

Docker volumes in the next article.....