Docker For Everyone Zero to Dev-ops to Developer

Vinay Prajapati
7 min readApr 15, 2020
Scared of Docker?

What Docker Actually is?

Basically, it is tool designed to optimally not just run but create, deploy and run applications using containers.

Wait what is container?

It allows a developer to take application with all of its parts e.g. lib's,APIs, DB and dependencies, and merge (ship) them in single package (image).

In Docker we can create containers. Containers can have application, APIs or processes inside an image. For Different Resources we can have Different Containers.

E.g. Container 1 Web Server, Container 2 Databases or Container 3 Kafka or Redis.

What is a docker image?

Actually, It is a file, compressed of many layers, it is used for execution of code in container.

How can I build an image?

Image is essentially built from the instructions for a complete and executable version of an application. which is relay on host operating system.

When it will be run it will be converted into multiple instances of that container.

Sounds like Virtual Machines right?

But, No it is not.

Infrastructure will be the same like any cloud or local-host. In case of Virtual Machine we have as many O.S. as VMs. but in Docker it will be single O.S. Virtual Machine we can not restrict dynamically but in docker we can do.

Volumes work on linux as well as containers.If we delete all containers in docker it won’t affect O.S. but Virtual Machine will delete O.S. and if you don’t want to delete O.S. probably, you have to delete every resources one by one too much time consuming.

How Docker is structured?

When you Install Docker in Machine. It Automatically, It will become Docker host(House of All containers).

After Installation of Docker there will be Server and Client. If you want to communicate to server you have to use REST APIs.

You will send request and will get resources.

Layers in Docker

Once Create an Image you can not change any layers in that image because images are read only. So, I can’t change this. Actually, you can but you have to create new image each and every time.

Now, you have Basic understanding let’s start with Installation

Install in Linux Server

Step 1. Always Update Repository.

Open Terminal and write (ctrl+alt+t):

sudo apt-get update

Step 2. Uninstall Old Version of Docker (Write this even If you don’t have old version)

sudo apt-get remove docker docker-engine docker.io

Step 3: Install Docker

sudo apt install docker.io

Step 4: Start a Docker

sudo systemctl start docker

Step 5. Enable a Docker

sudo systemctl enable docker

Step 6. Verify Docker Installation

docker — version

What is Docker Hub?

It is a remote Repository or Registry like GitHub but for docker images. you can push or pull from https://hub.docker.com/

Docker Commands

docker pull nginx (pull nginx Official Docker file from docker hub)

Get all Images we have

docker images

Remove Image from Container

docker rmi ngnix:1.16.0-alpine-perl (Image Name:Tag Name)

If you don’t Provide tag name then it will delete latest docker image

Create Container

docker run -d nginx

-d is for detached mode (optional)

Remove Container

docker rm 98972837de (docker rm tagname)

Run and Map Image to port

docker run -d -p 9090:80 ngnix:alpine

Check Docker Up and Running or Not

docker ps

Remove Running Docker

docker -f rm 98089324ee23 (using tagname)

Docker logs

docker logs apache11

Dockerfile

It is an instruction file which will generate image file automatically by reading this. Dockerfile.

Create Image file from Dockerfile

docker build — tag centos_apache:v1 . (It will pull centos image and will be follow instructions from Dockerfile)

From Instruction

From will pull image from docker hub

Run Instruction

You can search for different things, download resources, override and give user access etc.

Copy Instruction

Can copy installed or pulled resources to given location

ADD Instruction

Will Download resources for you.

LABEL Instruction

It adds meta data to Image.

EXPOSE Instruction

Allows you to configure a container that will run as an executable.

ARG Instruction

variable that users can pass at build time.

Environment variables in Docker

ENV HTML html-style (HTML is key and value is html-style)

CMD Instruction

CMD is providing defautls for an executing container. it may include an executable, or terminate executable. In this case you must specify an ENTERYPOINT instructions.

Context in Docker

Context is current directory. (.) is used for local directory.

Dockerignore

It can reduce Docker file size,speed up docker build and avoid unintended secret exposure. It can also help you to define the docker build context. Can be used for ignore rules and exceptions. Pattern matching syntax is same as go’s filepath.match() functions.

Best Practices while working with docker

Try to run only one service on docker container.

Build Context should be small

Avoid installing unnecessary packages

Less Layers in Docker image (Less Layers means Less RUN instruction)

Build Docker images with HTML-SSL + PHP

Step 1. Create Dockerfile and Write Code

FROM centos

RUN yum -y install httpd php

COPY html-ssl /var/www/html

RUN echo “<?php phpinfo() ?>” >/var/www/html/test.php

CMD apachectl -DFOREGROUND

Step 2. Run Docker Server

docker run -d -p 9090:80 — name apache apache_ssl:v1

If your port is already running check running port using (‘docker ps’) and remove using docker rm -f kkjjkl_2j23k

Step 3. SSL Certicate

openssl req -new -newkey rsa:2048 -days 365 -nodes -x509 -keyout docker.key -out docker.crtFill all details if asked after running this line.

Step 4. Install OpenSSL

sudo yum install mod_ssl openssl

Step 5. Copy the code mention below in to new file and name it as ssl.conf and change IP, email , DNS and details needed to be change.

<VirtualHost *:443>
ServerAdmin email@address
DocumentRoot “/var/www/html/adorkable/”
ServerName AdorkableDesigns
ServerAlias adorkable
ErrorLog /var/www/html/adorkable/error.log

<Directory “/var/www/html/adorkable/”>
DirectoryIndex index.html index.php
Options FollowSymLinks
AllowOverride All
Require all granted
</Directory>
</VirtualHost>

Run Docker to port machine to port container

docker run -d -p 443:443 — name apache_ssl apache_ssl:v3

Step 5. Provide path to Certificate

Copy below lines to ssl.conf in Virtualhost tag

SSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP

SSLCertificateFile /etc/ssl/star.example.com.crt
SSLCertificateKeyFile /etc/ssl/star.example.com.key

Step 6. Run Docker Again

docker run -d -p 43:43 — name apache_ssl apach_ssl:v1

Why should we build multi stage image?

Multi Stage Build will reduce the size of image.

Make sure you remove every artifacts before moving to new layer of image.

Better to have only one docker file which will have everything needed to run application.

Docker Volume

It is used for docker data persistence. It is virtual File System.

This are easier to back up or change bind mounts.

You can manage volumes using Docker CLI commands or using API.

Volumes work on linux as well as containers.

Volumes can be safely shared

Docker image push to docker hub

step1. docker login — username=vinay91098

hit enter then write password

step2. docker push vinay91098/<repo name>:<tag name>

If you get an error like denied: requested access to the resource is denied

Try this commands:-

docker tag bb38976d03cf yourhubusername/verse_gapminder:firsttry
docker push yourhubusername/verse_gapminder

Create Spring-boot maven file using docker

Step 1. Go to Spring Intializer (https://start.spring.io/) and click on java version, click on maven project, click on spring boot version

Step 2. Click on Generate

Step 3. pom.xml

<?xml version=”1.0" encoding=”UTF-8"?>
<project xmlns=”http://maven.apache.org/POM/4.0.0" xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>org.springframework</groupId>
<artifactId>gs-spring-boot-docker</artifactId>
<version>0.1.0</version>

<parent>

src/main/java/hello/Application.java

<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version>
</parent>

<properties>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build></project>

Step 4. Set up a Spring Boot app create a simple application.

src/main/java/hello/Application.java place file in this dir

package hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class Application {

@RequestMapping(“/”)
public String home() {
return “Hello Docker World”;
}

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

}

Step 5. execute maven

./mvnw package && java -jar target/projectname-0.1.0.java

Step 6. check code using localhost:8080

It will show “hello docker world”

Step 7. Create file using name Dockerfile in src folder and paste code written below

FROM openjdk:8-jdk-alpine
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar
ENTRYPOINT [“java”,”-jar”,”/app.jar”]

Step 8. run using maven

docker build -t springio/gs-spring-boot-docker . //(.) is used for current directry if you are not in current directry try using going to same directory as project is saved.

Create Spring-boot gradle file using docker

Step 1. Go to Spring Intializer (https://start.spring.io/) and click on java version, click on gradle project, click on spring boot version

Step 2. Click on Generate

Step 3. Create a Gradle build file name it asbuild.gradle

buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath(“org.springframework.boot:spring-boot-gradle-plugin:2.2.1.RELEASE”)
}
}

apply plugin: ‘java’
apply plugin: ‘eclipse’
apply plugin: ‘idea’
apply plugin: ‘org.springframework.boot’
apply plugin: ‘io.spring.dependency-management’

bootJar {
baseName = ‘gs-spring-boot-docker’
version = ‘0.1.0’
}

repositories {
mavenCentral()
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
compile(“org.springframework.boot:spring-boot-starter-web”)
testCompile(“org.springframework.boot:spring-boot-starter-test”)
}

Step 4. Set up a Spring Boot app create a simple application.

src/main/java/hello/Application.java place file in this dir

package hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class Application {

@RequestMapping(“/”)
public String home() {
return “Hello Docker World”;
}

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

}

Step 5. execute gradle project

./gradlew build && java -jar build/libs/gs-spring-boot-docker-0.1.0.jar

Step 6. Create file named as Dockerfile in springboot project

FROM openjdk:8-jdk-alpine
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java","-jar","/app.jar"]

Step 7. run using gradle

docker build --build-arg JAR_FILE=build/libs/*.jar -t springio/gs-spring-boot-docker .

We have created dockerfile is it sufficient?

No, not at all, we need to do optimization

--

--