How to create a new Docker image using Dockerfile: Dockerfile Example

Are you looking to create your own Docker image? The docker images are the basic software applications or an operating system but when you need to create software with advanced functionalities of your choice, then consider creating a new docker image with dockerfile.

In this tutorial, you will learn how to create your own Docker Image using dockerFile, which contains a set of instructions and arguments again each instruction. Let’s get started.

Join 50 other followers

Table of Content

  1. Prerequisites
  2. What is Dockerfile?
  3. Dockerfile instructions or Dockerfile Arguments
  4. Dockerfile Example
  5. Conclusion


If you’d like to follow along step-by-step, you will need the following installed:

  • Ubuntu machine with Docker installed. This tutorial uses Ubuntu 21.10 machine.
  • Docker v19.03.8 installed.

What is Dockerfile?

If you are new to dockerfile, you should know what dockerfile is. Dockerfile is a text file that contains all the instructions a user could call on the command line to assemble an image from a base image. The multiple instructions could be using the base image, updating the repository, Installing dependencies, copying source code, etc.

Docker can build images automatically by reading the instructions from a Dockerfile. Each instruction in DockerFile creates another layer (All the instructions take their own memory). While building the new image using the docker build command ( which is done by Docker daemon), if any instruction fails and if you rebuild the image, then previous instructions which are cached are used to build.

New Docker image can be built using simply executing docker build command, or if you need to build docker image from a different path use f flag.

docker build . 
docker build -f /path/to/a/Dockerfile .

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.

  • FROM : From instruction initializes new build stage and sets the base image for subsequent instructions. From instruction may appear multiple times in the dockerFile.
  • ARG: ARG is the only instruction that comes before FROM. The ARG instruction defines a variable that users can pass while building the image using the docker build command such as
 --build-arg <varname>=<value> flag
  • EXPOSE: Expose instruction informs docker about the port’s container listens on. The EXPOSE instruction does not actually publish the port.; it is just for the sake of understanding for admins to know about which ports are intended to be published
  • ENV: The ENV instruction sets the environment variable in the form of key-value pair.
  • ADD: The ADD instruction copies new files, directories, or remote file URLs from your docker host and adds them to the filesystem of the image.
  • VOLUME: The VOLUME instruction creates a mount point and acts as externally mounted volumes from the docker host or other containers.
  • RUN: The RUN instruction will execute any commands in a new layer on top of the current image and commit the results. RUN are declared in two ways, either shell way or executable way.
  • Shell way: the command is run in a shell i.e.,/bin/sh. If you need to run multiple commands, use the backslash.
  • Executable way: RUN [“executable”, “param1”, “param2”] . If you need to use any other shell than /bin/sh, you should consider using executable.
RUN /bin/bash -c 'source $HOME/.bashrc; echo $HOME' # Shell way
RUN ["/bin/bash", "-c", "echo HOME"] # Executable way (other than /bin/sh)
  • CMD: The CMD instruction execute the command within the container just like docker run exec command. There can be only one CMD instruction in DockerFile. If you list more than one then last will take effect. CMD has also three forms as shown below
    • CMD ["executable","param1","param2"] (exec form, this is the preferred form)
    • CMD ["param1","param2"] (as default parameters to ENTRYPOINT)
    • CMD command param1 param2 (shell form)

Let’s take an example in the below docker file; if you need that your container should sleep for 5 seconds and then exists, use the below command.

FROM Ubuntu
CMD sleep 5
  • Run the below docker run command to create a container, and then it sleeps for 5 seconds, and then the container exists.
docker run <new-image>
  • But If you wish to modify the sleep time such as 10 then either you will need to either change the value manually in the Dockerfile or add the value in the docker command.
FROM Ubuntu    
CMD sleep 10    # Manually changing the sleep time in dockerfile
  • Now execute the docker run command as shown below.
docker run <new-image> sleep 10  # Manually changing the sleep time in command line

You can also use the entry point shown below to automatically add the sleep command in the running docker run command, where you just need to provide the value of your choice.

FROM Ubuntu
ENTRYPOINT ["sleep"]

With Entrypoint, when you execute the docker run command with a new image, sleep will automatically get appended in the command as shown below. Still, the only thing you need to specify is the number of seconds it should sleep.

docker run <new-image> sleep <add-value-of-your-choice>

So in case of CMD command instruction command line parameters passed are completely replaced where in case of entrypoint parameters passed are appended.

If you don’t provide the <add-value-of-your-choice>, this will result in an error. To avoid the error, you should consider using both CMD and ENTRYPOINT but make sure to define both CMD and ENTRYPOINT in json format.

FROM Ubuntu    
ENTRYPOINT sleep       # This command will always run sleep command
CMD ["5"]              # In case you pass any parameter in command line it will be picked else 5 by default
  • ENTRYPOINT: An ENTRYPOINT allows you to run the commands as an executable in a container. ENTRYPOINT is preferred when defining a container with a specific executable. You cannot override an ENTRYPOINT when starting a container unless you add the --entrypoint flag.

Dockerfile Example

Up to now, you learned how to declare dockerfile instructions and executable of each instruction, but unless you create a dockerfile and build a new image with these commands, they are not doing much. So let’s learn and understand by creating a new dockerfile. Let’s begin.

  • Login to the ubuntu machine using your favorite SSH client.
  • Create a folder under home directory named dockerfile-demo and switch to this directory.
mkdir ~/dockerfile-demo
cd dockerfile-demo/
  • Create a file inside the ~/dockerfile-demo directory named dockerfile and copy/paste the below code. Below code contains from instruction which sets the base image as ubuntu and runs the update and nginx installation commands and builds the new image. Once you run the docker containter then Image created is printed on the screen on containers terminal using echo command.
FROM ubuntu:20.04
RUN apt-get update 
RUN apt-get install nginx 
CMD [“echo”,”Image created”] 
docker build -t docker-image:tag1 .
Building the docker image and tagging successfully
Building the docker image and tagging successfully

As you can see below, once the docker container is started, the Image created is printed on the container’s screen.

Running the container
Running the container

Join 50 other followers


In this tutorial, you learned what is dockerfile, a lot of dockerfile instructions and executables, and finally, how to create your own Docker Image using dockerFile.

So which application are you planning to run using the newly created docker image?


Ultimate docker interview questions for DevOps

If you are looking to crack your DevOps engineer interview, docker is one of the important topics that you should prepare. In this guide, understand the docker interview questions for DevOps that you should know.

Let’s go!

Join 50 other followers

Table of Content

Q1. What is Docker ?

Answer: Docker is lightweight containerized technology. It allows you to automate deployment in portable containers which is built from docker images.

Q2. What is Docker Engine.

Answer: Docker Engine is an server where docker is installed . Docker Client and server remains on the same server or remote host. Clients can connect with server using CLI or RESTful API’s.

Q3. What is use of Dockerfile and what are common instructions used in docker file?

Answer: We can either pull docker image and use it directly to build our apps or we can use it and on top of it we can create one more layer according to the need that’s where Dockerfile comes in play. With Docker file you can design the image accordingly. Some common instructions are FROM, LABEL, RUN , CMD

Q4. What are States of Docker Containers ?

Answer: Running , Exited , Restarting and Paused.

Q5. What is DockerHUB ?

Answer: Dockerhub is a cloud based registry for docker images . You can either pull or push your images in DockerHub.

Q6. Where are Docker Volumes stored ?

Answer: Docker Volumes are stored in /var/lib/docker/volumes.

Q7.Write a Dockerfile to Create and Copy a directory and built using Python Module ?


FROM Python:3.0
COPY . /app

Q8. What is the medium of communication between docker client and server?

Answer: Communication between docker client and server is taken care by REST API , socker.IO and TCP Protocol.

Q9. How to start Docker container and create it ?

Answer: Below command will create the container as well as run the container. Ideally just to create container you use docker container create “Container_name”

docker run -i -t centos:6

Q10.What is difference between EXPOSE PORT and PUBLISH Port ?

Answer: Expose Port means you just exposes it locally i.e to container only . Publish Port means you are allowing from outside World.

Q11. How can you publish Port i.e Map Host to container port ? Provide an example with command


Here p is mapping between Host and container and -d is dettached mode i.e container runs in background and you just see container ID displayed on

docker container run -d -p 80:80 nginx

Q12. How do you mount a volume in docker ?


docker container run -d --name "My container"  --mount  source="vol1",target=/app  nginx

Q13. How Can you run multiple containers in single service ?

Answer: We can achieve this by using docker swarm or docker compose. Docker compose uses YAML formatted files.

Q14. Where do you configure logging driver in docker?

Answer: We can do that in file daemon.jason.file.

Q15. How can we go inside the container ?


docker exec -it "Container_ID"  /bin/bash

Q16. How can you scale your Docker containers?

Answer: By using Docker compose command.

docker-compose --file scale.yml scale myservice=5

Q17. Describe the Workflow from Docker file to Container execution ?

Answer: Docker file ➤ Docker Build ➤ Docker Image (or Pull from Registry) ➤Docker run -it ➤ Docker Container ➤Docker exec -it ➤Bash

Q18. How to monitor your docker in production ?


docker stats : Get information about CPU , memory and usage etc.

docker events : Check activities of containers such as attach , detach , die, rename , commit etc.

Q19. Is Docker swarm an approach to orchestrate containers ?

Answer: Yes it is one of them and other is kubernetes

Q20. How can you check docker version?

Answer: docker version command which gives you client and server information together.

Q21. How can you tag your Docker Image ?

Answer: Using docker tag command.

docker tag "ImageID" "Repository":tag


In this guide, you learned some of the basic questions around the docker interview questions for DevOps that you should know.

There is some more interview guide published on; which one did you like the most?

How to create Node.js Docker Image and Push to DockerHub using Jenkins Pipeline

If you plan to run your node.js application, nothing could be better than running on the docker and safely storing it on Dockerhub.

Running an application on docker is a huge benefit because of its light-weighted technology and security. Docker images are stored safely on the dockerhub

In this tutorial, you will learn how to create a docker image for node.js applications and push it to dockerhub using the Jenkins pipeline.

Let’s get started.

Join 50 other followers

Table of Content

  1. What is Jenkins Pipeline?
  2. What is Jenkinsfile?
  3. What is node.js server-side javascript?
  4. Prerequisites
  5. How to Install node.js and node.js framework on ubuntu machine
  6. Creating Node.js Application
  7. How to create dockerfile for Node.js application
  8. Pushing all the code to GIT Repository: Git Push
  9. Creating Jenkinsfile to run docker image of Node.js application
  10. Configure Jenkins to Deploy Node.js Docker Image and Push to Dockerhub
  11. Conclusion

What is Jenkins Pipeline?

Jenkins Pipeline uses a group of plugins that help deliver a complete continuous delivery pipeline starting from building the code till deployment of the software right up to the customer.

Jenkins Pipeline plugin is automatically installed while installing the Jenkins with suggested plugins and allows you to write complex operations and code deployment as code using DSL language ( Domain-specific language).

Related: the-ultimate-guide-getting-started-with-Jenkins-pipeline

What is Jenkinsfile?

Jenkins Pipelines uses a text file called Jenkinsfile, which is checked into the repository. You define each stage and steps that need to be executed, such as building and compiling code to deploy in respective environments.

Jenkinsfile allows you to define steps in code format, which is easier and gives more ability to review. In case Jenkins stops, you can still continue to write Jenkinsfile. It can hold, wait, approve, stop Jenkins job and many other functionalities.

What is node.js server-side javascript?

JavaScript is a language used with other languages to create a web page add some dynamic features such as rollover or graphics, and Node.js is an open-source JavaScript runtime environment.

Node.js performs well as it contains only a single process without wasting much memory, CPU and never blocks any threads or processes and furthermore allows multiple connections simultaneously.

Node.js allows JavaScript developers to create apps in the front and backend.


  • You must have ubuntu machine preferably 18.04 version + and if you don’t have any machine you can create a ec2 instance on AWS account
  • Docker and Jenkins must be installed on ubuntu machine.
  • Make sure you have git hub account and a repository created . If you don’t have follow here

How to Install node.js and node.js framework on ubuntu machine

Now that you know what is node.js and what are benefits of having node.js. In this section, let’s dive into how to Install node.js and node.js frameworks on ubuntu machines.

  • Log in to the Ubuntu machine using your favorite SSH client.
  • Now, create a folder named nodejs-jenkins under opt directory in the ubuntu machine.
cd /opt
mkdir nodejs-jenkins
cd nodejs-jenkins
  • Now install node.js on ubuntu machine using the below command.
sudo apt install nodejs
  • Next, Install node.js package manager. Installing node.js package manager allows to install modules node_modules inside the same directory.
sudo apt install npm
  • Further install Nodejs express Web Framework and initialize it. This command will generate package.json file containing the project, all the dependencies and metadata details that will be used to create a project and further application.
npm init
  • Further, add one dependency which is required by node.js application.
npm install express --save

Creating Node.js Application

Now that you have successfully installed the node.js application and framework required to create a node.js application. Let’s create a node.js application.

Assuming you are still logged into the ubuntu machine.

  • Firstly, create a file named main.js in the /opt/nodejs-jenkins directory and copy/paste the below code.
var express = require('express')    //Load express module with `require` directive
var app = express() 

//Define request response in root URL (/)
app.get('/', function (req, res) {
  res.send('Hello Welcome to')
app.listen(8081, function () {
  console.log('app listening on port 8081!')

How to create dockerfile for Node.js application

Previously you created a node.js application, which is great, but to deploy node.js on docker, you will need to create a dockerfile. Docker file creates customized docker images on top of docker images.

After creating the dockerfile, you can use the docker build command to create a new customized docker image.

Running docker containers using dockerfile
Running docker containers using dockerfile

Let’s jump in and create a dockerfile for the node.js application.

  • Create a file named dockerfile in the same /opt/nodejs-jenkins directory and copy/paste the below content.
FROM node:7              # Sets the base image
RUN mkdir -p /app
WORKDIR /app             # Sets the working directory in the container
COPY package.json /app   # copy the dependencies file to the working directory
RUN npm install          # Install dependencies
COPY . /app       # Copy the content of the local src directory to the working directory
CMD ["npm", "run", "start"]
  • Next, to create a node.js docker image using above dockerfile run the below command on ubuntu machine.
docker build .
Building the docker image using dockerfile
Building the docker image using dockerfile

Pushing all the code to GIT Repository: Git Push

Earlier, you created the node.js application and manually built the docker image to confirm that your code is absolutely fine and works. Let’s push all the files and code in the Git repository using various commands so that later Jenkins can use these files and build the application.

  • Now your directory /opt/nodejs-jenkins should have look as below.
checking the content of the directory
checking the content of the directory
  • Initialize a new repository in the same directory /opt/nodejs-jenkins by running git init command.
git init
  • Add all the file in git repository using the below command in the same directory /opt/nodejs-jenkins
git add .
  • Now, check the status of git repository with below command. If there are any errors they will appear else you are good to go to the next step.
git status
  • Commit your changes in git repository using the git commit command in the same directory /opt/nodejs-jenkins
 git commit -m "MY FIRST COMMIT"
  • Add the remote repository that you already had as a origin by running git remote add command.
git remote add origin
Adding the remote origin
Adding the remote origin
  • Finally push the changes in the remote branch . Once prompted specify your credentials.
git push -u origin master
Pushing the code in git repository
Pushing the code in git repository
  • Now, verify the code on github by navigating to the repository link.
Verifying the git repository
Verifying the git repository

Creating Jenkinsfile to run docker image of Node.js application

Let’s quickly jump into the creation of Jenkinsfile to run docker image of Node.js application to deploy an application using Jenkins.

  • Create a file named Jenkinsfile in the same /opt/nodejs-jenkins directory and copy/paste the below content. Make sure to change the sXXXXXXX410/dockerdemo as per you’re dockerhub username and repository name.
node {
     def app 
     stage('clone repository') {
      checkout scm  
     stage('Build docker Image'){
      app ="sXXXXX410/dockerdemo")
     stage('Test Image'){
       app.inside {
         sh 'echo "TEST PASSED"' 
     stage('Push Image'){
       docker.withRegistry('', 'git') {            
  • Now push the Jenkinsfile as well in github in the same repository that you used earlier. Now, your repository should look something like below.
Pushing the Jenkinsfile in the git repository
Pushing the Jenkinsfile in the git repository

Configure Jenkins to Deploy Node.js Docker Image and Push to Dockerhub

Now that you have all the code, including Jenkinsfile, in the Github repository and deploy the node.js application on docker using Jenkinsfile, you need to create a Jenkins Job. Let’s configure Jenkins by creating a new multi-branch pipeline Jenkins Job.

  • Create a new multibranch pipeline Jenkins Job named nodejs-image-dockerhub by clicking on new item and selecting multibranch pipeline on the Dashboard.
Creating a new multibranch pipeline Jenkins Job
Creating a new multibranch pipeline Jenkins Job
  • Now click on nodejs-image-dockerhub job and click on configure it with git URL and then hit save.
Configuring the Git URL in the Jenkins
Configuring the Git URL in the Jenkins
  • To connect to dockerhub you would need to add dockerhub credentials by clicking on the Dashboard ➔ Manage Jenkins ➔ Manage credentials ➔ click on global ➔ Add credentials.
Adding the dockerhub credentials in the Jenkins
Adding the dockerhub credentials in the Jenkins
  • Next, on Jenkins server add Jenkins user in the docker group so that Jenkins user has access to run docker commands.
sudo groupadd docker
sudo usermod -a -G docker jenkins
service docker restart
  • Further, make sure Jenkins users has sudo permissions by running below commands.
sudo vi  /etc/sudoers
  • Now you are ready to run your first jenkins job. click on scan Multibranch pipeline job that will scan your branches in the repository. Then click on Branch and then click on Build Now.
Running the Jenkins Job
Running the Jenkins Job
  • The Jenkins job is completed successfully. Lets verify if Docker image has been successfully pushed to dockerhub by visiting Dockerhub repository.
Checking the docker image in dockerhub


In this tutorial, you learned what the Jenkins pipeline is, node.js is, and how to create a dockerfile, Jenkins file, and node.js application. Finally, you pushed the docker image to dockerhub using Jenkins.

So now you know how to deploy the node.js application on docker; which application do you plan to deploy next?