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 .
Run the command docker images
to check if the image has been created
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
Run the command docker ps
to check if your container is running
#a list of files/folders you don't want copied into your docker image
#dockerignorefile
node_modules
dockerfile
Main Docker Commands
- docker ps - shows a list of all running containers
- docker images - shows all images in your machine
- docker rm - removes one or more containers
- docker rmi - removes one or more images
- docker stops- stops one or more running containers
- docker kill - kills one or more running containers without a cleanup process
- 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
Great work!!๐, you just Dockerized your Nodejs Application
Docker volumes in the next article.....