How to Create Dockerfile step by step and Build Docker Images using Dockerfile

If you want to create your own Docker images rather than already cooked Docker images, consider using Dockerfile, the layer-based docker image building file.

Docker file is used to create customized docker images on top of basic docker images using various arguments such as FROM, ADD, CMD, etc.

In this tutorial, you will learn everything about Dockerfile, how to create Dockerfile, and create a customized docker image.

Let’s jump in to understand each bit of it.

Join 28 other followers

Table of Content

  1. What is Dockerfile?
  2. Prerequisites
  3. How to Create Dockerfile ( Dockerfile commands )
  4. Dockerfile instructions or Dockerfile Arguments
  5. Docker cmd vs entrypoint
  6. How to Create Docker Image and run a container using Dockerfile
  7. Dockerfile example using multiple Docker Arguments
  8. Conclusion

What is Dockerfile?

Dockerfile is used to create customized docker images on top of basic docker images using a text file that contains all the commands to build or assemble a new docker image. Using the docker build command, you can create new customized docker images.

Once a new Docker image is created, you can further use the docker image to launch docker containers and run.

Launching a new Docker container using a new Docker image created using Dockerfile
Launching a new Docker container using a new Docker image created using Dockerfile

Prerequisites

  • You must have ubuntu machine preferably 18.04 plus version and if you don’t have any machine you can create an AWS EC2 instance on AWS account
  • Docker must be installed on ubuntu machine. To install Docker on ubuntu machine follow here.

How to Create Dockerfile ( Dockerfile commands )

Now that you have a basic idea about what Dockerfile is and how it helps you launch a new Docker image of your choice and further Docker container from it. Let’s discuss some of the important aspects of Dockerfile and how to create a Dockerfile.

There are two forms in which Dockerfile can be written that is shell form and other is exec form.

  • The Syntax of Shell form command is:
Shell form <instruction> command
# Shell form
ENV name John Dow
ENTRYPOINT echo "Hello, $name"
  • The Syntax of exec form command is:
Exec form <instruction> ["executable", "param1", "param2"]
# exec form
RUN ["apt-get", "install", "python3"]
CMD ["/bin/echo", "Hello world"]
ENTRYPOINT ["/bin/echo", "Hello world"]
  • Environmental variables inside Dockerfile can be declared as $var_name or ${var_name}
WORKDIR ${HOME}  # This is equivalent to WORKDIR ~
ADD . $HOME      # This is equivalent to ADD . ~

Dockerfile instructions or Dockerfile Arguments

Now that you have a basic idea about what is docker and dockerfile, let’s understand some of the most important Dockerfile instructions or Dockerfile Arguments that are used in the Dockerfile.

  • FROM command is used to set a base Docker image. For example in the below command ubuntu:14.04 is set as the base docker image.
FROM base:${CODE_VERSION}

FROM ubuntu:14.04
  • RUN command executes commands when the Docker container starts.

RUN lets you execute commands inside of your Docker image however CMD lets you define a default command to run when your container starts. 

RUN echo $VERSION
# RUN <command> (shell form)
# RUN ["executable", "param1", "param2"] (exec form)
  • ADD command will add all the files from the host to docker images. Below command will add a file from folder directory kept at host to containers /etc directory.
ADD folder/file.txt /etc/

ADD directive is more powerful in two ways as it can handle remote URLs and can also auto-extract tar files.

  • CMD command will set the default command if you don’t specify any command while starting an container.
    • It can be overridden by user passing an argument while running the container.
    • If you apply multiple CMD command only last takes effect
CMD ["Bash"]
  • Maintainer allows you to add author details
MAINTAINER support@automateinfra.com
  • EXPOSE command informs docker about the port which container should listen on
    • Below are are setting a container to listen on port 8080
EXPOSE 8080
  • The ENV command sets an environment variable in the new container
    • Below we are setting HOME environments variable to /root
ENV HOME /root
  • USER command Sets the default user within the container
USER ansible
  • VOLUME command creates a shared volume that can be shared among containers or by the host machine
VOLUME ["/var/www", "/var/log/apache2", "/etc/apache2"]
  • WORKDIR command set the default working directory for the container
WORKDIR app/
  • ARG command allows users to pass at build-time with the docker build command .
    • Syntax  --build-arg <varname>=<value> 
ARG username
  • ARG arugument
docker build  --build-arg username=automateinfra 
  • LABEL instruction adds metadata to an image and it uses key value pair
LABEL 
  • SHELL command allows to overwrite the use of default shell.
    • SHELL command will overwrite the use of [“/bin/sh”,”-c”] in case of linux shell
    • SHELL command will overwrite the use of [“cmd”,”/S”,”/C”] in case of windows shell
# Executed as cmd /S /C echo -command Write Host default
RUN powershell -command Write-Host default

# Executed as PowerShell  -command Write-Host hello
SHELL ["PowerShell", "-command"]
RUN Write-Host hello
  • ENTRYPOINT is also used for running the command but with a difference from CMD command
    • In case of ENTRYPOINT command if you give command line argument ENTRYPOINT doesn’t allow to override it.

Docker cmd vs entrypoint

In this section learn what is the docker cmd vs entry point docker arguments as these are the most widely used and important arguments one must know.

Create a Dockerfile containing the following code which included the CMD argument.

FROM nginx
CMD [“echo”, “Hello World”]
  • Next create a docker Image followed by running a docker container using CMD argument.
docker build . 
# Run a container normally without CMD argument
sudo docker run [image_name]
# Run a container using CMD argument.
sudo docker run [image_name] hostname

You will notice that the CMD argument is completely overwritten with the argument that you pass on the command line argument.

running a docker container using CMD argument
running a docker container using CMD argument

Now, update the Dockerfile containing the following code with the ENTRYPOINT argument.

FROM nginx
ENTRYPOINT  [“echo”, “Hello World”]
  • Next create a docker Image followed by running a docker container using ENTRYPOINT argument.
docker build . 
# Run a container normally without ENTRYPOINT  argument
sudo docker run [image_name]
# Run a container using ENTRYPOINT argument.
sudo docker run [image_name] hostname

You will notice that the ENTRYPOINT argument is appended when you pass the command line argument.

running a docker container using ENTRYPOINT argument
running a docker container using ENTRYPOINT argument

How to Create Docker Image and run a container using Dockerfile

Now that you have sound knowledge of how Dockerfile is created using different commands. Let’s now dive in and learn some basics Dockerfile examples to get you started.

  • Login to ubuntu machine using your favorite SSH Client.
  • Create a folder named dockerfile-demo1 under opt directory.
cd /opt
mkdir dockerfile-demo1
cd dockerfile-demo1
  • Create a named Dockerfile inside the /opt/dockerfile-demo1 directory and copy/paste the below code. The commands which Dockerfile will use are:
    • FROM: It sets the base image as ubuntu
    • RUN: It runs the following commands in the container
    • ADD: It adds the file from a folder
    • WORKDIR: It tells about the working directory
    • ENV: It sets a environment variable
    • CMD: Its runs a command when the container starts
FROM ubuntu:14.04
RUN \
    apt-get -y update && \
    apt-get -y upgrade && \
    apt-get -y install git curl unzip man wget telnet
ADD folder/.bashrc /root/.bashrc
WORKDIR /root
ENV HOME /root
CMD ["bash"]

The syntax to build docker Image from Dockerfile is shown below.

docker build .        # Command 1
# Provide the exact path where Dockerfile is located
docker build -f /path-of-Dockerfile .       # Command 2
  • Now, build a Docker Image using the docker build command.
 docker build -t image1 .
Building a docker image
Building a docker image
  • Lets verify the Docker Image by running the following command.
docker images
Verifying the docker images
Verifying the docker images
  • Now, its time to check if Docker Image is successfully working by running a container and verifying all the Dockerfile commands inside the container.
docker run -i -t 5d983653b8f4

Great, you will notice that the commands declared in Dockerfile are executed in the below snap. The new docker Image was created successfully, which further you tested by launching a docker container.

Running the docker container
Running the docker container

Dockerfile example using multiple Docker Arguments

In this section, let’s look at another Dockerfile example using multiple Docker Arguments. Assuming you are still logged into the ubuntu machine.

  • Create another folder named dockerfile-demo2 under opt directory.
mkdir dockerfile-demo2
cd dockerfile-demo2
  • Create a Dockerfile with your favorite editor inside the /opt/dockerfile-demo2 directory and copy/paste the below content into it.
FROM ubuntu:14.04
ARG LABEL_NAME
LABEL org.label-schema.name="$LABEL_NAME"
SHELL ["/bin/sh", "-c"]
RUN apt-get update && \
    apt-get install -y sudo curl git gcc make openssl libssl-dev libbz2-dev libreadline-dev libsqlite3-dev zlib1g-dev libffi-dev
USER ubuntu
WORKDIR /home/ubuntu
ENV LANG en_US.UTF-8
CMD [“echo”, “Hello World”]
  • Now, build a Docker Image using the following command
 docker build --build-arg LABEL_NAME=mylabel  -t imagetwo .
build a Docker Image
build a Docker Image
  • Lets verify the Docker Image by running the following command.
docker images
Verifying the Docker Image
Verifying the Docker Image
  • Also verify the new Docker Image by running a container and verifying all the Dockerfile commands inside the container.
docker run -i -t 2716c9e6c4af
Verifying the Docker Image by running a container
Verifying the Docker Image by running a container
docker run -i -t 2716c9e6c4af /bin/bash
  • Lets navigate inside the container and check other details as well.
    • User is ubuntu
    • Working directory is /home/ubuntu
    • Curl is installed
    • ENV LANG is also set.
Checking commands in docker container
Checking commands in docker container
  • Finally if you want to check LABEL then use the docker inspect command by specifying the docker image.
docker inspect 2716c9e6c4af
Checking LABEL in docker container using docker inspect command
Checking LABEL in docker container using docker inspect command

Conclusion

This tutorial taught you in-depth commands used inside Dockerfile to build a Docker Image. There are several commands which we covered using examples in the demonstration.

Also, you learned how to create docker images, run containers, and verify if those commands were executed successfully. Dockerfile is essential for building new Docker Images on top of the base Docker image.

Which docker image do you plan to create using a customized Dockerfile and run containers?

How to Install Docker ubuntu step by step

If you want to deploy multiple applications in an isolated environment, consider using Docker and containers where applications have their own container.

In this tutorial, you’ll install the Docker ubuntu machine. You’ll then work with docker containers and docker images and push an image to a Docker Repository. So let’s get started.

Let’s dive in.

Join 28 other followers

Table of Content

  1. What is Docker?
  2. Prerequisites
  3. How to Install Docker on Ubuntu 18.04 LTS
  4. How to run Docker command using Non-Root user (run docker commands without sudo)
  5. Working with docker command ( docker pull command, docker ps, docker image)
  6. Tag Docker image using docker tag and push docker image to docker hub
  7. Conclusion

What is Docker?

Docker is an open-source tool for developing, shipping, and running applications. It has the ability to run applications in a loosely isolated environment using containers. Docker is an application that helps manage containers in a very smooth and effective way. In containers, you can isolate your applications. Docker is quite similar to a virtual machine, but it is lightweight and easily ported.

Containers are light weighted as they are independent of hypervisors load and configuration. They directly connect with machines, i.e., the host’s kernel.

What is Docker?
What is Docker?

Prerequisites

  • Ubuntu machine preferably 18.04 version +, if you don’t have any machine you can create an ec2 instance on AWS account
  • Recommended to have 4GB RAM and at least 5GB of drive space.
  • An account on Docker Hub if you wish to create your own images and push them to Docker Hub.

You may incur a small charge for creating an EC2 instance on Amazon Managed Web Service.

How to Install Docker on Ubuntu 18.04 LTS

Let’s kick off this tutorial by installing docker on ubuntu. Installing docker on the ubuntu machine is a straightforward task. The Docker installation package is available in the official Ubuntu repository may not be the latest version.

This tutorial will install Docker from the official Docker repository to ensure you get the latest version. To do that, add a new package source, add the GPG key from Docker to ensure the downloads are valid, and then install the package.

  • Login to your Ubuntu machine using your favorite SSH client.
  • First, update your existing list of packages by running the below command
sudo apt update
  • Install the below prerequisites software so that apt uses packages over the https protocol. The apt transport software allows your machine to connect with external repositories over HTTPS or HTTP over TLS.
sudo apt install apt-transport-https ca-certificates curl software-properties-common

  • Next, add the GPG key for the official Docker repository to your system. This key builds the trust of your machine with the docker official repository.
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

  • Now, add the Docker repository to APT sources so that you can install the docker installation package.
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu bionic stable"

  • Next, update the package database with the Docker packages from the newly added repo using the following command.
sudo apt update
  • Finally, Install the docker on the ubuntu machine using the apt install command.
sudo apt install docker-ce

  • Docker should be started by now; verify the status and version of docker by using service docker status the command.
Checking the docker service using service docker status command
Checking the docker service using the service docker status command

How to run Docker command using Non-Root user (run docker commands without sudo)

The docker command can only be run by the root user or by a user in the docker group, automatically created during Docker’s installation process. If you attempt to run the docker command without prefixing it with sudo or without being in the docker group, it will give you a permission denied error message.

  • To enable users other than root or to run docker commands without sudo, first create the docker group using the groupadd docker command.
groupadd docker
  • Next, add the users in the docker group that you created earlier and can run Docker commands.
sudo usermod -aG docker jenkins   # To add Jenkins user to docker group
sudo usermod -aG docker user1     # To add user1 to docker group
sudo usermod -aG docker ubuntu    # To add ubuntu user  to docker group
  • Restart the docker service by service docker restart command.
service docker restart 
  • Check the docker version by running the below command.
docker version

Your docker commands should now run succesfully now without giving any permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock like this, if you continue to get this message make sure to logout and login back on your machine.

Verifying the docker version using docker version command
Verifying the docker version using the docker version command

Working with docker command ( docker pull command, docker ps, docker image)

The most important part of docker is to run several docker commands such as docker pull which fetches docker images that contain your code, the environment to run it, and several parameters. Docker images are stored on the Docker repository known as the docker hub, though you can also store them on your local machine.

Docker architecture
Docker architecture
  • Use the docker pull command to pull the docker image on your ubuntu machine.
docker pull ubuntu
Pulling an image from docker repository using docker pull command on ubuntu machine
Pulling an image from docker repository using docker pull command on ubuntu machine
  • Now check the downloaded image on your ubuntu machine and run the docker images command.
docker images
Checking all docker images in the system
Checking all docker images in the system
  • Now, run the first docker container by using the below command.
docker run -it ubuntu # Here i,t provides you interactive shell access and ubuntu is image name
Running docker container using docker run command
Running docker container using docker run command.
  • To check all container details ( Exited, running, etc.), run the docker ps -a command.
 docker ps -a
Checking details of all container details
Checking details of all container details

Tag Docker image using docker tag and push docker image to docker hub

Now, let’s learn how to push the docker image to the docker hub. You need a docker hub account to push the docker image to the docker hub.

Assuming you are still logged into the Ubuntu machine using the SSH client.

  • Login to docker hub with your credentials and then login.
docker login -u docker-registry-user
Login to docker hub using docker login -u command
Login to docker hub using docker login -u command
  • Before you push your docker image to the docker hub, it’s highly recommended to tag your image with your docker hub username using the docker tag command. The syntax of the docker tag command is docker tag image.
docker tag ubuntu:latest  <dockerhub-username>/ubuntu:latest
  • After successful login in docker hub, now push your docker image using the following command.
docker push <dockerhub-username>/ubuntu:latest
Running docker push command
Running docker push command.

As you can see below, the docker image is successfully pushed into the docker hub that you created on the ubuntu machine.

successfully pushed docker image into docker hub
successfully pushed docker image into docker hub

Join 28 other followers

Conclusion

In this tutorial, you learned how to install Docker, learned several docker commands such as docker images, docker tag, docker pull, and how to push docker image to docker hub.

Docker is a great way to host your applications separately and efficiently. So which applications are you planning to run in docker?