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

There were days when a organization use to get physical server and a system administrator was asked to make the system ready within months like Installing OS, Adding Software’s and Network configuration and finally applications use to get deployed in months.

Now the same work can be done in literally 5 minutes . Yes it can be done by launching docker containers using Dockerfile ( Layer based ) docker image building file. If you would like to know more follow along.

In this this tutorial we will learn everything about Dockerfile , how to create Dockerfile and commands used inside Dockerfile also known as Docker Instruction. These Dockerfile further can be used to create customized docker image. Lets jump in to understand each bit of it.

Table of content

  1. What is Dockerfile?
  2. Prerequisites
  3. How to Create Dockerfile ( Dockerfile commands or Dockerfile Instructions)
  4. How to build a Docker Image and run a container using Dockerfile
  5. Conclusion

What is Dockerfile?

Docker file is used to create a customized docker images on top of basic docker image. It is a text file that contains all the commands to build or assemble a new docker image. Using docker build command we can create new customized docker images . Its basically another layer which sits on top of docker image. Using newly built docker image we can run containers in similar way.

This image has an empty alt attribute; its file name is image-43.png

Prerequisites

  • 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 must be installed on ubuntu machine. If you don’t have follow here

How to Create Dockerfile ( Dockerfile commands)

  • There are two forms in which docker file can be written
    • Shell form <instruction> command
    • Exec form <instruction> [“executable”, “param1”, “param2”]
# Shell form
ENV name John Dow
ENTRYPOINT echo "Hello, $name"
# exec form
RUN ["apt-get", "install", "python3"]
CMD ["/bin/echo", "Hello world"]
ENTRYPOINT ["/bin/echo", "Hello world"]
  • To build docker Image from Dockerfile
docker build .        or

docker build -f /path-of-Docker-file .
  • Environmental variables inside Docker file can be written as $var_name or ${var_name}
WORKDIR ${HOME}  # This is equivalent to WORKDIR ~
ADD . $HOME      # This is equivalent to ADD . ~
  • FROM command is used when we need to build a new Docker Image using Base Image
    • Below command will set ubuntu:14.04 as the base image.
FROM base:${CODE_VERSION}

FROM ubuntu:14.04
  • RUN command is executed while building the image that is on top of the current image and then creates a new layer. You can run multiple RUN commands in Dockerfile
RUN echo $VERSION
# RUN <command> (shell form)
# RUN ["executable", "param1", "param2"] (exec form)
  • ADD command will add all the files from the host to container
    • Below command will add a file from folder directory kept at host to containers /etc directory
ADD folder/file.txt /etc/
  • 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"]

EXAMPLE

  • Lets assume a single line Docker file containing following code
CMD [“echo”, “Hello World”]
  • Lets create a docker Image
docker build . 
  • Run a container to see CMD command actions
sudo docker run [image_name]
  • Check the Output of the command
O/p:  Hello World
  • Run a container with an argument to see CMD command actions
sudo docker run [image_name] hostname
  • Check the Output of the command
O/P: 067687387283 # Which is containers hostname
  • Maintainer allows you to add author details
MAINTAINER support@automateinfra.com
  • EXPOSE helps to inform 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
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.

EXAMPLE

  • Lets assume a single line Docker file containing following code
ENTRYPOINT  [“echo”, “Hello World”]
  • Lets create a docker Image
docker build . 
  • Run a container to see ENTRYPOINTcommand actions
sudo docker run [image_name]
  • Check the Output of the command
O/p:  Hello World
  • Run a container with an argument to see ENTRYPOINT command actions
sudo docker run [image_name] parameter
  • Check the Output of the command
O/P: Hello World parameter

How to Create Docker Image and run a container using Dockerfile

Now we should be good with how Dockerfile is created using different commands. Lets now dive in to see some of the examples to get you started.

EXAMPLE 1

  • Create a folder under opt directory and name it as dockerfile-demo1
cd /opt
mkdir dockerfile-demo1
cd dockerfile-demo1
  • Create a Dockerfile with your favorite editor
vi Dockerfile
  • Command which we will use for Dockerfile
    • 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
  • Paste the below content
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"]
  • Now, build a Docker Image using the following command
 docker build -t image1 .
  • Lets verify the Docker Image by running the following command.
docker images
  • Now, its time to check if Docker Image is successfully working . So lets run a container and then verify all the Dockerfile commands inside the container.
docker run -i -t 5d983653b8f4
Looks Great, we can see all the commands which we used in Docker file were executed and Docker Image was created . We tested this on one of the container built using Docker Image.

EXAMPLE 2

  • Create a folder under opt directory and name it as dockerfile-demo2
cd /opt
mkdir dockerfile-demo2
cd dockerfile-demo2
  • Create a Dockerfile with your favorite editor
vi Dockerfile
  • Paste the below content
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 .
  • Lets verify the Docker Image by running the following command.
docker images
  • Now, its time to check if Docker Image is successfully working . So lets run a container and then verify all the Dockerfile commands inside the container.
docker run -i -t 2716c9e6c4af
  • CMD command ran successfully
  • As we defined a custom CMD which displays the echo command and exits out of container. Lets go inside the container and check other details.
    • User is ubuntu
    • Working directory is /home/ubuntu
    • Curl is installed
    • ENV LANG is also set.
docker run -i -t 2716c9e6c4af /bin/bash
  • Finally if you want to check LABEL command then you can see it on host by inspecting the docker image.
docker inspect 2716c9e6c4af

Looks Great, we can see all the commands which we used in Docker file were executed and Docker Image was created . We tested this on one of the container built using Docker Image.

Conclusion

In this tutorial we learnt in depth commands used inside Dockerfile to build a Docker Image . There are several commands which we covered using examples in the demonstration.

Also we learnt how to create docker image and run containers and verify if those commands were executed successfully. Dockerfile is very important concept for building new Docker Images on top of Base Docker image.

Now, you’re ready with how to create Dockerfile and using Dockerfile create Image and run containers. Hope this tutorial will help you with Docker concepts. Please share if you like.

How to run Node.js applications on Docker Engine

Table of content

  1. What is Node.js ?
  2. What is docker ?
  3. Prerequisites
  4. How to Install Node.js on ubuntu machine
  5. Install Node.js Express Web Framework
  6. Create a Node.js Application
  7. Create a Docker file for Nodejs application
  8. Build Docker Image
  9. Run the Nodejs application on a Container
  10. Conclusion

What is Node.js ?

Node.js is an open source JavaScript runtime environment. Now, what is JavaScript ? Basically JavaScript is a language which is used with other languages to create a web page and add some dynamic features such as roll over and graphics.

Node.js runs as a single process without wasting much of memory and CPU and never blocks any threads or process which is why its performance is very efficient. Node.js also allows multiple connections at the same time.

With the Node.js it has become one of the most advantage for JavaScript developer as now they can create any apps utilizing it as both frontend or as a backend.

Building applications that runs in the any browser is a completely different story than than creating a Node.js application although both uses JavaScript language.

What is docker ?

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

Containers are light weighted as they are independent of hypervisors load and configuration. They directly connect with machines ie. hosts kernel.

Prerequisites

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

How to Install node.js on ubuntu machine

  • Update your system packages.
sudo apt update
  • Lets change the directory and Download the node js package
cd /opt

sudo apt install nodejs
  • Install node js package manager
sudo apt install npm
  • Verify the node js package installation
nodejs -v

Install Nodejs Express Web Framework

  • Install Nodejs Express Web Framework and initialize it
npm init
  • package.json which got created after initializing the Nodejs framework will have all the dependencies which are required to run. Let us add one dependency which is highly recommended.
npm install express --save

CREATE NODE.JS APPLICATION

main.js

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 Automateinfra.com')
})


app.listen(8081, function () {
  console.log('app listening on port 8081!')
})
  • Now Run the Node.js application locally on ubuntu machine to verify
node main.js
This image has an empty alt attribute; its file name is image-38.png

Create a docker file for Node.js application

Docker file is used to create a customized docker images on top of basic docker image. It is a text file that contains all the commands to build or assemble a new docker image. Using docker build command we can create new customized docker images . Its basically another layer which sits on top of docker image. Using newly built docker image we can run containers in similar way.

This image has an empty alt attribute; its file name is image-43.png
  • Create a docker file and name it as Docker file . Keep this file also in same directory as main.js
FROM node:7              # Sets the base image
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 node main.js         # Command to run on container start  
EXPOSE 8081

Build a Docker Image

  • Now we are ready to build our new image . So lets build our image
docker build -t nodejs-image .
  • You should see the docker images by now.
docker images

Run the Nodejs application on a Container

  • Now run our first container using same docker image ( nodejs-image)
docker run -d -p 8081:8081 nodejs-image
  • Verify if container is successfully created.
docker ps -a

Great, You have dockerized Nodejs application on a single container .

This image has an empty alt attribute; its file name is image-38.png

Conclusion:

In this tutorial we covered what is docker , what is Nodejs and using Nodejs application created a application on docker engine in one of the containers.

Hope this tutorial will helps you in understanding and setting up Nodejs and Nodejs applications on docker engine in ubuntu machine.

Please share with your friends.

How to Setup Docker step by step on Ubuntu machine

I am sure most of you have installed lots of application on single Virtual machine and faced challenges while maintaining them and facing memory or system issues and things become more ugly when you troubleshoot each application to fix the problem.

What should one do ? Cannot we isolate our apps so that we can easily find the problem ? Cant one app which is not working should be down and others should run as it is ? Yes, that correct that’s very much possible with docker and containers. They provide you isolated environment and are your friend for deploying many applications with each taking its own container.

In this tutorial, you’ll install and use Docker on Ubuntu 18.04. You’ll then work with containers , images and push an image to a Docker Repository. So lets get started.

Table of Content

  1. What is Docker ?
  2. Prerequisites
  3. How to Install Docker on ubuntu machine
  4. How to run Docker commands using Non Root user
  5. Working with docker images and containers
  6. Pushing docker images to docker hub
  7. Conclusion

What is Docker ?

🐟Docker is an open source tool for developing , shipping and running applications. It has ability to run applications in loosely isolated environment using containers. Docker is an application which helps in management of containers in a very smooth and effective way. In containers you can isolate your applications. Docker is quite similar to virtual machine but it is light weighted and can be ported easily.

Containers are light weighted as they are independent of hypervisors load and configuration. They directly connect with machines ie. hosts kernel.

Prerequisites

  • Ubuntu machine preferably 18.04 version + , if you don’t have any machine you can create a ec2 instance on AWS account
  • Recommended to have 4GB RAM
  • 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

sudo apt update
  •  Install some required packages for apt so that it can use over https
sudo apt install apt-transport-https ca-certificates curl software-properties-common
  • Add the GPG key for the official Docker repository to your system
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key --keyring /etc/apt/trusted.gpg.d/docker.gpg add -
  • Add the Docker repository to APT sources
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
sudo apt update
  • Now, Install docker
sudo apt-get update && sudo apt-get install -y \
  containerd.io=1.2.13-2 \
  docker-ce=5:19.03.11~3-0~ubuntu-$(lsb_release -cs) \
  docker-ce-cli=5:19.03.11~3-0~ubuntu-$(lsb_release -cs)
  • Docker should be started now, verify the status and version of docker.
  • Check the docker version
  • Docker is successfully installed and now you are reading to work with docker and containers.

How to run Docker commands using Non Root user

To enable users other than root and users with sudo access to be able to run Docker commands:

  1. Create the docker group
groupadd docker
  1. Add the users that should have Docker access to the docker group
sudo usermod -a -G docker jenkins   # To add Jenkins user to docker group
sudo usermod -a -G docker user1     # To add user1 to docker group
  1. Restart the docker service by following command
# The UNIX socket /var/run/docker.sock is now writable by members of the docker group.

service docker restart 

Working with docker images and containers

Most important part in docker is docker images which contains your code , environment to run it and several parameters. Docker images are stored on docker repository known as docker hub , though you can store it on your local machine as well.

  • To pull docker image ubuntu on your system
docker pull ubuntu
  • Now check the downloaded image.
docker images
  • In this tutorial we are providing the demo so we will use the same pulled docker image and run our first container , but you can update the same image with more configurations or as per requirements as well.
  • Run the first container
docker run -it ubuntu                # Here i and t provides you interactive shell access and ubuntu is image name
  • We used exit to come out of shell , so container has been exited. To check the containers details.
 docker ps -a

Pushing docker images to docker hub

  • Firstly you will need to login to docker hub with your credentials and then login.
docker login -u docker-registry-user
  • Before you push your docker image to docker hub , its highly recommended to to tag your image with your docker hub username .
docker tag ubuntu:latest  <dockerhub-username>/ubuntu:latest
  • After successful login in docker hub now push your docker image
docker push <dockerhub-username>/ubuntu:latest

Conclusion

In this tutorial you installed Docker, worked with images and containers, and pushed a image to Docker Hub

Hope this tutorial will help you in understanding and setting up Docker on ubuntu machine. Please share with your friends.