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

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 . .

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

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

node_modules
npm-debug.log

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> .
  • . - means the current working directory, will use the dockerfile in that directory.
  • -t - will add a tag to the image
  • image-name - the name of the image
  • tag - the tag of the image your creating, latest is standard.

Other important build flags

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

  • -f, --file - path to Dockerfile if another name or in another directory
  • --no-cache - force rebuild without using cache
  • --rm - remove intermediate containers after build

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>
  • -d - means detached, it will happen in the background.
  • -p - specifies which port to use. In this case 49160 locally, and 8080 within the container.

Other important run flags

  • --name - set a name to the container
  • --rm - remove container when it exists

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>