How To Create a Docker Image, Build and Push It To Docker Hub

This is a simple explanation of the Docker workflow. From creating the first Dockerfile to pushing it to Docker.

Docker workflow

without going into any details, this simply describes the workflow when creating a Docker image and all code that is necessary to know.

1. Create a Dockerfile in the root directory, modify it

This is an example of a simple node application. Nothing I will get into now. This is just about the workflow.

Create the file with touch Dockerfile.

FROM node:10

WORKDIR /usr/src/app

COPY package*.json ./

RUN npm install

COPY . .

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

You can also include a .dockerignore file to prevent local modules to be copied into Docker.


2. Build the image

Based on the Dockerfile, we can build an image with the following command. We need to include the username so that we can push it to Docker Hub later.

docker build -t <username>/<image-name>:<tag> .

Other important build flags

Some other flags you might use when building a Docker image.

3. Run the Docker container

You can run the container (based on the image we created) locally with the following command.

docker run -d -p 49160:8080 <image-name>:<tag>

Other important run flags

If you want to enter the container, you can use the exec command. You will need to use the container id which you can get by writing docker ps.

docker exec -it <container-id> /bin/bash

4. Push the Docker container to Docker Hub

Finally, you can push the image to Docker Hub to share it.

docker push <username>/<image-name>