How to create a docker image

If you are here, then I am assuming you would have knowledge of what docker is and why do we use it.

You might have seen plenty of images in dockerhub, so now let’s create a simple docker image.

Dockerfile

To create any docker image we first need to write some code for it, and that has to be written in a file called Dockerfile (this name can be changed, but conventionally it is named like this).

A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image.

There are a few commands we need to learn before writing a dockerfile.

In this example we will be creating a Docker image for a node-express backend application.

Let us assume right now we have a Dockerfile, in our node-express project directory.

  1. FROM base_image: this is mostly (99.99% of times) the first step while creating any dockerfile.
FROM node:latest

let us see what this line means, FROM node:latest

Since we are creating docker image for express application, so we need an environment that will support node, in that case we are using base image node:latest. In case we needed to run java application in the docker image, we would have used image which would support java environment.

  1. WORKDIR path: This is used to create and move the control to the directory path inside the docker image
FROM node:latest
WORKDIR /usr/src/app
  1. COPY source destination: This command will copy files and folders from the path source(in your local workstation) to destination (inside the docker container).
FROM node:latest
WORKDIR /usr/src/app
COPY . /usr/src/app

COPY . /app will copy all the files in the current directory and move them to /app in the container image.

  1. RUN Command: This is used to run any command inside the container. Let’s say for any node project we will need to install node modules before we can start application.
FROM node:latest
WORKDIR /usr/src/app
COPY . /usr/src/app
RUN npm install

RUN npm install will run npm install command inside the container.

  1. EXPOSE port_number: This used to expose a port of docker container to outside network. If the correct port is not exposed, then outside traffic can not connect to the docker container server. here we specify the port number of our application server.
FROM node:latest
WORKDIR /usr/src/app
COPY . /usr/src/app
RUN npm install
EXPOSE 3000
  1. CMD [commands]: Here we pass the command, which will be used to run our application server.

FROM node:latest

WORKDIR /usr/src/app

COPY . /usr/src/app

RUN npm install

EXPOSE 3000

CMD ['node', 'server.js']

Now we have created our dockerfile, now we need to build our docker image.

docker build

To create a docker image from a docker file we use docker build command.


docker build -t image_name source

lets say we want to name our docker image node_app we will build it as


docker build -t node_app .

This will build our docker image.