0% found this document useful (0 votes)
50 views73 pages

03 AG Create & Manage Docker Ed28

Uploaded by

dbstudies07
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views73 pages

03 AG Create & Manage Docker Ed28

Uploaded by

dbstudies07
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 73

Create & Manage Docker

(Container, Image, Networking,


Volume, Dockerfile)
[Edition 28]

[Last Update 221224]

[email protected] 1
Contents
1 Introduction .........................................................................................................................................................4
2 Documentation ....................................................................................................................................................5
2.1 Linux Commands and VIM Commands ................................................................................................................ 5
3 Pre-Requisite .......................................................................................................................................................6
4 Docker installation steps on Ubuntu 20.04 server .................................................................................7
5 Working with Container................................................................................................................................ 10
5.1.1 Exposing the container port ...........................................................................................................................................11
3. 4 Working with Docker Images .............................................................................................................. 13
3. 5 Docker Default Bridge Networking.................................................................................................... 20
3. 6 Creating Custom Bridge Network ....................................................................................................... 26
3. 7 Docker Host Network.............................................................................................................................. 29
3. 8 Docker Storage – Host Path Mounting .............................................................................................. 31
3. 9 Docker Volume .......................................................................................................................................... 35
3. 10 Docker Private Registry ......................................................................................................................... 37
3. 11 Working with Dockerfile ....................................................................................................................... 39
5.2 ARG in Dockerfile ...................................................................................................................................................... 43
5.3 Using ARG variables ................................................................................................................................................. 43
5.4 Docker Volume .......................................................................................................................................................... 44
5.5 USER in Dockerfile .................................................................................................................................................... 44
3. 12 Docker Compose ....................................................................................................................................... 46
5.6 Compose V2 and the new docker compose command................................................................................. 46
5.7 Working with Application Stack .......................................................................................................................... 46
3. 13 Configuring External DNS, Logging and Storage Driver .............................................................. 53
3. 14 Multi-stage Dockerfile ............................................................................................................................ 56
3. 15 Multi-stage Dockerfile Another Example......................................................................................... 59
3. 16 Troubleshooting ....................................................................................................................................... 61
5.8 Getting error while restarting docker service after configuring external dns, logging & storage
driver......................................................................................................................................................................................... 61
5.9 Issue: Access Denied Error Lab-6 ........................................................................................................................ 62
5.10 Can’t pull Apache2 Image ................................................................................................................................... 63
5.11 Getting Error While Build and run the application with docker-compose Lab-14 ....................... 64
5.12 Unable to Docker Login or Create a new Docker ID ................................................................................. 68
5.13 Apache2 page not showing ............................................................................................................................... 68
5.14 http://hostip:5000 -> This site can’t be reached ...................................................................................... 69
5.15 Web container is in exit state ........................................................................................................................... 69
5.16 Runtime Error: invalid memory address when doing docker login ................................................... 70
3. 17 Extra Docker Question ........................................................................................................................... 72
3. 18 Summary ..................................................................................................................................................... 73

[email protected] 2
[email protected] 3
1 INTRODUCTION
Docker is a platform for developers and sysadmins to build, run, and share applications
with containers. The use of containers to deploy applications is called containerization.
Containers are not new, but their use for easily deploying applications is.

Containerization is increasingly popular because containers are:

• Flexible: Even the most complex applications can be containerized.


• Lightweight: Containers leverage and share the host kernel, making them much
more efficient in terms of system resources than virtual machines.
• Portable: You can build locally, deploy to the cloud, and run anywhere.
• Loosely coupled: Containers are highly self sufficient and encapsulated, allowing
you to replace or upgrade one without disrupting others.
• Scalable: You can increase and automatically distribute container replicas across a
datacenter.
• Secure: Containers apply aggressive constraints and isolations to processes without
any configuration required on the part of the user.

[email protected] 4
2 DOCUMENTATION

1. Docker Container
https://docs.docker.com/engine/reference/commandline/container/
2. docker container attach
https://docs.docker.com/engine/reference/commandline/container_attach/
3. docker container create
https://docs.docker.com/engine/reference/commandline/container_create/
4. Docker Image
https://docs.docker.com/engine/reference/commandline/images/
5. Docker File Refrence
https://docs.docker.com/engine/reference/builder/

2.1 Linux Commands and VIM Commands

3. 1 Basic Linux Commands


https://maker.pro/linux/tutorial/basic-linux-commands-for-beginners
https://www.hostinger.in/tutorials/linux-commands
3. 2 Basic VIM Commands
https://coderwall.com/p/adv71w/basic-vim-commands-for-getting-started
3. 3 Popular VIM Commands
https://www.keycdn.com/blog/vim-commands

[email protected] 5
3 PRE-REQUISITE
Ensure that you have completed following two activity guides (or you have an Ubuntu
Server)
• Create account (Trial or Paid) on Azure Cloud.
Note: Follow Activity Guide
Register_For_Azure_Cloud_Account_Accessing_Console_ed** from portal

• Installed Ubuntu Server (configure at least 2 vCPU) Note: Follow Activity Guide
Create_&_Connect_to_Ubuntu_Server_ed** from portal

• Linux for beginners’ course to make yourself familiar with vi editor and basic Linux
commands. If you are new to Linux, then ask for the FREE Bonus course.

[email protected] 6
4 DOCKER INSTALLATION STEPS ON UBUNTU 20.04 SERVER

1. [Optional] Only if docker was already installed on this host and you want to configure it again
Uninstall Old Versions of Docker.
(Older versions of Docker were called docker, docker.io, or docker-engine. If these are
installed, uninstall them)
$ sudo apt-get remove docker docker-engine docker.io containerd runc
2. Update the apt package
$ sudo apt-get update

3. Install packages to allow apt to use a repository over HTTPS:


$ sudo apt-get install \
ca-certificates \
curl \
gnupg \
lsb-release
4. Add Docker’s official GPG key:

(Note: Copy and paste the command on a notepad first then execute it.)
$ sudo mkdir -p /etc/apt/keyrings
$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o
/etc/apt/keyrings/docker.gpg
5. Use the following command to set up the stable repository.
(Note: The below is a single command, please Copy and paste the command on a notepad
first then execute it.)

$ echo \
"deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg]
https://download.docker.com/linux/ubuntu \
$(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

Note: Above command is in single line like below (first copy paste in notepad and then from
notepad paste on Linux terminal)

echo \
"deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg]
https://download.docker.com/linux/ubuntu \
$(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

[email protected] 7
6. Update apt package again

$ sudo apt-get update

7. Install Docker Engine.


$ sudo apt-get install docker-ce docker-ce-cli containerd.io docker-compose-plugin

Note: If you hit any error then refer to troubleshooting section

8. Start and Enable Docker


$ sudo systemctl start docker
$ sudo systemctl enable docker

9. Check Docker status


$ sudo systemctl status docker

10. Identify the user id of user that will run container


$ id

11. Add above user to docker group

$ sudo usermod -aG docker <userid>

$ sudo usermod -aG docker DockerMachineUser

12. Logout and log back in and check if user has group docker assigned

[email protected] 8
Note: If you don’t logout and log back in you may get error like below at later stage

13. Check Docker Version


docker --version

[email protected] 9
5 WORKING WITH CONTAINER
1. Creating first Container
$ docker run -it ubuntu bash

Or

$ docker container run -it ubuntu bash

Note: If you don’t logout and log back in you may get error like below at later stage

2. Update Software Repositories inside the Container


root@bc35381ed053:/# apt-get update

3. Quit from Container without stopping it


Press Ctrl p Ctrl q

4. List the running Containers


$ docker ps

$ docker container ls

[email protected] 10
5. List all Containers
$ docker ps -a

$ docker container ls -a

6. List the images in Local Repository


$ docker images

5.1.1 EXPOSING THE CONTAINER PORT

To access a container we first need to expose it’s port. We can use the options “-p” and “-P”.
‘-p’ - Publish a container's port(s) to the host
‘-P’ - Publish all exposed ports to random ports

1. Deploy an nginx container by exposing its port to 8080.


$ docker run --name web1 -dit -p 8080:80 nginx

2. List the container


$ docker ps

[email protected] 11
3. Now we can access the app running inside the container from browser using the Public ip of
the host machine and the port like below-

http://<PublicIP>:8080

4. Deploy an nginx container by exposing its port to any random port using ‘-P’
$ docker run --name web2 -dit -P nginx

It has exposed to a random port i.e. 49153, Now we can access it using it.

[email protected] 12
3. 4 WORKING WITH DOCKER IMAGES

1. Pull Docker Image from Public Docker Repo


$ docker pull alpine:3.6
OR
docker image pull alpine:3.6

2. List Image by name and tag


$ docker images alpine:3.6

3. List full length Image ID


$ docker images --no-trunc

4. Listing out Images with Filter


$ docker images --filter=reference='alpine'

5. Inspect Image details


$ docker inspect alpine:3.6

[email protected] 13
6. Commit Container to create Container Image
$ docker ps
$ docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]
$ docker commit bc35381ed053 ubuntu:new

7. Verify by listing the newly create Image


$ docker images

8. List running Containers


$ docker ps
OR

$ docker container ls

[email protected] 14
9. Export Container as tar file (Persisting Container)
$ docker export bc3538 > ubuntu.tar
$ ls -lrt

10. Commit this tar as a new image locally


$ docker import - myubuntu < ubuntu.tar
$ docker images

11. Save Image as tar file (Persisting Image)


$ docker pull nginx

$ docker images nginx

[email protected] 15
$ docker save -o mynginx1.tar nginx
$ ls -lrt

12. Delete Images from Local repo


$ docker rmi nginx:latest

13. Load Image back from tar file


$ docker images

$ docker load < mynginx1.tar

$ docker images nginx

14. Create your own registry at https://hub.docker.com by signing up

[email protected] 16
15. Tag and Push image to Docker Hub

a) Login at the command line terminal with your Docker ID created in above step to push and
pull images from Docker Hub

$ docker login

Note: Replace mamtaj with your Docker Hub Login ID

b) We will tag the image with the registry name to push it to our named registry
So the format of tagging is:

[email protected] 17
docker tag SOURCE_NAME:TAG TARGET_NAME:TAG
TAGRET_NAME is above command should be of format:
Registry/repository:tagname

Note: Replace mamtaj with your Docker Hub Login ID


$ docker tag nginx:latest mamtaj/nginx:latest
$ docker images

c) Push the image with docker push command

Note: Replace mamtaj with your Docker Hub Login ID


$ docker push mamtaj/nginx:latest

d) Verify that the image is pushed to our registry at https://hub.docker.com

[email protected] 18
[email protected] 19
3. 5 DOCKER DEFAULT BRIDGE NETWORKING

1. Listing types of network


$ docker network ls

2. Inspect Bridge type network


$ docker network inspect bridge

3. List network driver plugins

[email protected] 20
$ docker info

4. Stop all containers


$ docker ps
$ docker stop <container id>

[email protected] 21
5. Install brctl tools
$ sudo apt-get install bridge-utils

6. Check the Bridge and Ip Address details


$ brctl show

$ ip a

7. Start container on default Bridge network


$ docker start <Container Id>

[email protected] 22
Inspect the Bridge network
docker0 bridge will have 1 new interfaces connected
$ brctl show

$ docker network inspect bridge

8. Test network connectivity from the server


$ ping 172.17.0.2

9. Create one more container and check the ip address


$ docker run -it ubuntu bash
Enter Ctrl p + q, to exit from the container

[email protected] 23
$ brctl show

$ docker network inspect bridge

10. Connect to Container and check network connectivity


$ docker attach bc35381ed

root@70268afd27cd:/# apt-get update


root@70268afd27cd:/# apt-get install iputils-ping

[email protected] 24
11. Check if you are able to reach the other container on the same network
$ ping 172.17.0.3

12. Try to ping google.com and check internet connectivity inside the Container
$ ping google.com

[email protected] 25
3. 6 CREATING CUSTOM BRIDGE NETWORK

1. Creating Custom network of type Bridge


$ docker network create --driver bridge custom-bridge

2. List the Networks


$ docker network ls

3. Create two containers and connect to custom-bridge


$ docker run -dt --network custom-bridge --name=Cont1 ubuntu bash

$ docker run -dt --network custom-bridge --name=Cont2 ubuntu bash

4. Inspect the custom-bridge network


$ docker network inspect custom-bridge

[email protected] 26
5. Connect to Container Cont1 and install iputils-ping
$ docker exec -it Cont1 bash

root@9227d60ab1d3:/# apt-get update

root@9227d60ab1d3:/# apt-get install iputils-ping

6. Check networking between containers on custom-bridge Bridge


root@9227d60ab1d3:/# ping Cont2

[email protected] 27
7. Check internet connectivity
root@9227d60ab1d3:/# ping google.com

8. Check connectivity with Container on docker0 Bridge


root@9227d60ab1d3:/# ping 172.17.0.2

Enter Ctrl p + q, to exit from the container

[email protected] 28
3. 7 DOCKER HOST NETWORK

1. Create and start the container as a detached process on Host network


$ docker run --rm -d --network host --name my_nginx nginx

2. Verify if container is created


$ docker ps

Note: To access nginx please use your azure machine host IP address. Also all port should be
open. To Open ports please refers to the Create_&_Connect_to_Ubuntu_Server_ed**

3. Open web browser of docker host and verify is the server is serving Nginx

[email protected] 29
4. Verify which process is bound to port 80, using the netstat command.
$ sudo netstat -tulpn | grep :80

5. Stop the container.


$ docker container stop my_nginx

[email protected] 30
3. 8 DOCKER STORAGE – HOST PATH MOUNTING

1. Create a directory on Docker Host


$ mkdir /home/vol-share
2. Create container named "volsharing1" and mount the host path to container
$ docker run -it -p 80:80 -v /home/vol-share:/var/www/html --name volsharing1 ubuntu
/bin/bash

3. Update repo inside Container, Install and Start apache


root@148fb089759a:/# apt-get update -y
root@148fb089759a:/# apt-get install apache2 -y
root@148fb089759a:/# apt-get install vim -y
root@148fb089759a:/# service apache2 start
root@148fb089759a:/# service apache2 status
4. Customise the web page
root@926f93bf594c:/# vim /var/www/html/index.html
At line number 198 change the text to “Apache2 page from volsharing1"

Note: If you don’t know how to edit files in Linux


a. Click “I” button to enter inside the Insert mode

[email protected] 31
b. Move Your Curser using arrow keys go to the line number 198

c. Click on ESC button and Exit Insert mode and type :wq! to save and exit file

[email protected] 32
Save and quit from the file. Exit from the container without stopping it.
(Ctrl p+q)
5. Create container named "volsharing2" and mount the same host path to container
$ docker run -it -p 81:80 -v /home/vol-share:/var/www/html --name volsharing2 ubuntu
/bin/bash

6. Update repo inside Container, Install and Start apache


root@037c6320f4f6:/# apt-get update -y
root@037c6320f4f6:/# apt-get install apache2 -y
root@037c6320f4f6:/# service apache2 start
root@037c6320f4f6:/# service apache2 status
7. Open Docker Host web browser and try and access both container web page
You will see both the containers are serving the same page and the content is persistent on
the host path.

Note: To access Apache please use your azure machine host IP address. Also all port should be
open. To Open ports please refers to the Create_&_Connect_to_Ubuntu_Server_ed**

[email protected] 33
[email protected] 34
3. 9 DOCKER VOLUME

1. Creating docker volume named “volume1”


$ docker volume create volume1

2. List docker volumes


$ docker volume ls

3. Inspect the created volume


$ docker inspect volume1

4. Create container named "busybox-cont" and mount docker volume "volume1" @ /data in the
container
$ docker run -it -v volume1:/data --name busybox-cont busybox:latest

5. Create a file in the mounted volume path


# cd /data
/data # echo "Hi from docker volume" > vol.txt

[email protected] 35
6. Quit from the "busybox-cont" container without exitting it
Press below keys in sequence Ctrl p + ctrl q
Enter Ctrl p + q, to exit from the container

7. Create container named "other-container" and mount docker volume "volume1" @ /data in the
container
$ docker run -it -v volume1:/data --name other-container busybox:latest
8. Look for the vol.txt file in "other-container" @ /data
/ # cd /data
/data # cat vol.txt

Enter Ctrl p + q, to exit from the container

[email protected] 36
3. 10 DOCKER PRIVATE REGISTRY

1. Create a local directory to store docker images


$ sudo mkdir -p /registry/images
2. Create container to serve private registry using registry image from Docker Hub
$ docker run -d -p 5000:5000 --name registry -v /registry/images:/var/lib/registry --restart
always registry:2

3. List the running containers


$ docker ps

4. Pull image from Docker public repo


$ docker pull jenkins

5. Tag image to push it to Private Registry

[email protected] 37
$ docker tag jenkins:latest localhost:5000/jenkins:latest

6. Push image to Private Registry


$ docker push localhost:5000/jenkins:latest

7. Verify image is saved at the /registry/images path


$ cd /registry/images/docker/registry/v2/repositories/
$ ls

[email protected] 38
3. 11 WORKING WITH DOCKERFILE

1. Creating a directory named Dockerfile and in it create dockerfile named as dockefile


$ mkdir Dockerfile
$ cd Dockerfile

$ vim Dockerfile

Note: In Lab 10 Docker Storage - host path mounting, steps available for how to Edit/Save Files.
2. Add the following code to the dockerfile:
FROM ubuntu
RUN apt-get update
RUN apt-get install -y nginx
COPY index.nginx-debian.html /var/www/html
EXPOSE 80
COPY [“./start.sh”, ”/root/start.sh”]
ENTRYPOINT /root/start.sh

Note: when you copy this file from here Please retype the [“ ”] again manually otherwise in
later steps you will get the below error.
When you copy this from here the double quotes need to type again in file.

[email protected] 39
3. Create sample index.html file in the same directory
$ vim index.nginx-debian.html

4. Add the following welcome message to the index file:


WELCOME TO NGINX.

5. Create script start.sh file in the same directory. Add the below content to start nginx daemon
on start. Also change the script file permission to executable.
$ vim start.sh

[email protected] 40
$ chmod 777 start.sh

6. Execute the Dockerfile (note that there is a space between build and .)
$ docker build .

7. Check if the Docker Image has been creates


$ docker images

8. Tag the newly create image and verify


$ docker tag 53b851849970 nginxbuilt

$ docker images

9. Use “nginxbuilt” image to start an nginx container

[email protected] 41
$ docker run -d -p 82:80 nginxbuilt

10. Connect to the container to verify if nginx service is up and running


$ docker exec -it 053f13225a8e bash
root@053f1322a8e:/# service nginx status

Note: To access nginx please use your azure machine host IP address. Also all port should be
open. To Open ports please refers to the Create_&_Connect_to_Ubuntu_Server_ed**

11. Login to Docker Host web browser at port 82 and check if Nginx website is served

[email protected] 42
5.2 ARG in Dockerfile
1. The ARG instruction defines a variable that users can pass at build-time to the builder with the
docker build command using the --build-arg <varname>=<value> flag. If a user specifies a build
argument that was not defined in the Dockerfile, the build outputs a warning.
FROM busybox
USER ${user:-some_user}
ARG user
USER $user
A user builds this file by calling:
$ docker build --build-arg user=what_user .
The USER at line 2 evaluates to some_user as the user variable is defined on the subsequent line
3. The USER at line 4 evaluates to what_user as user is defined and the what_user value was
passed on the command line.

5.3 Using ARG variables


1. You can use an ARG or an ENV instruction to specify variables that are available to the RUN
instruction. Environment variables defined using the ENV instruction always override an ARG
instruction of the same name. Consider this Dockerfile with an ENV and ARG instruction.
FROM ubuntu
ARG CONT_IMG_VER
ENV CONT_IMG_VER=v1.0.0
RUN echo $CONT_IMG_VER
Then, assume this image is built with this command:
[email protected] 43
$ docker build --build-arg CONT_IMG_VER=v2.0.1 .
In this case, the RUN instruction uses v1.0.0 instead of the ARG setting passed by the user:v2.0.1
This behavior is similar to a shell script where a locally scoped variable overrides the variables
passed as arguments or inherited from environment, from its point of definition.

5.4 Docker Volume


1. The VOLUME instruction creates a mount point with the specified name and marks it as
holding externally mounted volumes from native host or other containers.
FROM ubuntu
RUN apt-get update && apy-get install -y iputils-ping
VOLUME /data
ENTRYPOINT [“echo”]

5.5 USER in Dockerfile


The USER instruction sets the user name (or UID) and optionally the user group (or GID) to use
when running the image and for any RUN, CMD and ENTRYPOINT instructions that follow it in the
Dockerfile.
By default, a Docker Container runs as a Root user. This poses a great security threat if you
deploy your applications on a large scale inside Docker Containers. You can change or switch to a
different user inside a Docker Container using the USER Instruction. For this, you first need to
create a user and a group inside the Container.
FROM ubuntu:latest
RUN apt-get -y update
RUN groupadd -r teacher && useradd -r -g teacher Ramesh
USER Ramesh
Build Image
docker build .

[email protected] 44
Check user and groups
$ docker run -it 6c2f395762ba bash

[email protected] 45
3. 12 DOCKER COMPOSE

Note: Docker Compose is now part of the Docker CLI it can be installed via a convenience script
with Docker Engine and the CLI. We have already installed it while installing docker.

5.6 Compose V2 and the new


docker compose command
The new Compose V2, which supports the compose command as part of the Docker CLI, is now
available.
Compose V2 integrates compose functions into the Docker platform, continuing to support most of
the previous docker-compose features and flags. You can run Compose V2 by replacing the
hyphen (-) with a space, using docker compose, instead of docker-compose.

5.7 Working with Application


Stack
1. Create a directory for the project
$ mkdir stackdemo
$ cd stackdemo
2. Create a file called app.py in the project directory and the below code
$ vim app.py
Or
$ git clone https://github.com/k21academyuk/docker

Add the following code in it:


import time
import redis

[email protected] 46
from flask import Flask

app = Flask(__name__)
cache = redis.Redis(host='redis', port=6379)

def get_hit_count():
retries = 5
while True:
try:
return cache.incr('hits')
except redis.exceptions.ConnectionError as exc:
if retries == 0:
raise exc
retries -= 1
time.sleep(0.5)

@app.route('/')
def hello():
count = get_hit_count()
return 'Hello World! I have been seen {} times.\n'.format(count)
Note: file indenting python is very sensitive on the line indention

[email protected] 47
3. Create a file called requirements.txt
$ vim requirements.txt
Add the following text in it:
flask
redis

4. Create a file called Dockerfile


$ vim Dockerfile
FROM python:3.7-alpine
WORKDIR /code
ENV FLASK_APP app.py
ENV FLASK_RUN_HOST 0.0.0.0
RUN apk add --no-cache gcc musl-dev linux-headers
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
COPY . .
CMD ["flask", "run"]
Note: when you copy this file from here Please retype the [“ ”] again manually otherwise in
later steps you will get the error.
When you copy this from here the double quotes need to type again in file.
Add the following code in it:

5. Create a file named docker-compose.yml and add the below code


$ vim docker-compose.yml
[email protected] 48
version: '3'
services:
web:
build: .
ports:
- "5000:5000"
redis:
image: "redis:alpine"

6. Build and run the application with docker-compose


$ docker compose up -d

[email protected] 49
7. Verify the application running

Enter http://hostip:5000/ in a browser to see the application running

8. List the application running as part of the stack using compose commands
$ docker compose ps

$ docker ps

9. Edit the Compose file to add a bind mount

Edit docker-compose.yml in to add a bind mount for the web service:

[email protected] 50
10. Re-build and run the app with Compose
$ docker compose up -d

11. Update the application without having to re-build it

Because the application code is now mounted into the container using a volume, we can
make changes to its code and see the changes instantly, without having to rebuild the image.

Open a new terminal and change the greeting in app.py and save it. For example, change
the Hello World! message to Hello from Docker Container!:

[email protected] 51
12. Verify the application running is updated on the fly

Enter http://hostip:5000/ in a browser to see the application running

13. Bring the application down


$ docker compose down

[email protected] 52
3. 13 CONFIGURING EXTERNAL DNS, LOGGING AND STORAGE DRIVER

1. Attach to a nginx container


Note: If no nginx container is running on your system then please create one
$ docker attach 20a9b14eabaf

2. Verify the resolv.conf file content


$ cat /etc/resolv.conf

Enter Ctrl p+Ctrl q

3. Create/Update /etc/docker/daemon.json to use external DNS for all containers


$ vim /etc/docker/daemon.json
{
"dns": ["8.8.8.8"]
}
4. Restart Docker service
$ sudo service docker restart
5. Create another container and verify its /etc/resolv.conf file content to verify that new DNS
server details
$ docker container run -d --name nginx7 nginx

[email protected] 53
$ docker exec -it nginx7 cat /etc/resolv.conf

6. Making Logging driver changes in /etc/docker/daemon.json file

7. Restart Docker service


$ sudo service docker restart
8. Use the following command to check the current default logging driver
$ docker info --format “{{.LoggingDriver}}”

9. Start container with specific Logging driver and verify


$ docker run -it --log-driver journald --name nginxlog nginx bash

Enter Ctrl p+Ctrl q

$ docker inspect -f “{{.HostConfig.LogConfig.Type}}” nginxlog

10. Verify present Storage driver configured


$ docker info | grep -i storage
[email protected] 54
11. Making Storage driver changes in /etc/docker/daemon.json file

12. Restart Docker service and verify the storage driver configured
$ sudo service docker restart
$ docker info | grep -i storage

[email protected] 55
3. 14 MULTI-STAGE DOCKERFILE

1. Clone Git
$ git clone https://github.com/k21academyuk/Multi-stage-Guide
$ cd Multi-stage-Guide/

2. Execute the Dockerfile for Single stage (note that there is a space between build and .)
docker build -f Dockerfile.singlestage -t single_stage .

[email protected] 56
3. Check Image Size
docker images

4. Execute the Dockerfile for multi stage (note that there is a space between build and .)
docker build -f Dockerfile.multistage -t multi_stage .

5. Check Image Size


docker images

[email protected] 57
[email protected] 58
3. 15 MULTI-STAGE DOCKERFILE ANOTHER EXAMPLE

1. Clone Git
$ git clone https://github.com/k21academyuk/Multi-stage-Guide_1
$ cd golang-http-server/

2. Execute the Dockerfile for Single stage (note that there is a space between build and .)
docker build -f Dockerfile -t single1-small .

[email protected] 59
3. Check Image Size
docker images

4. Execute the Dockerfile for multi stage (note that there is a space between build and .)
docker build -f Dockerfile.multi -t multi1-small .

5. Check Image Size


docker images

[email protected] 60
3. 16 TROUBLESHOOTING

5.8 Getting error while restarting


docker service after
configuring external dns,
logging & storage driver
Issue: Getting error while restarting docker service after configuring external dns, logging &
storage driver

Reason: /etc/docker/daemon.json file is not configured properly.

Fix: please add coma(,) after every key: value pair like below.

[email protected] 61
5.9 Issue: Access Denied Error
Lab-6

[email protected] 62
Solution: Wrong login ID Used
Tagged image with Wrong Id
docker id: emrypala

docker tag nginx:latest emrypala/nginx:latest (To tag)


docker push emrypala/nginx:latest (To Push Image)

5.10 Can’t pull Apache2 Image


Issue: When trying to pull Apache Image getting error like pull access denied for apache,
repository does not exist or may require 'docker login': denied: requested access to the resource is
denied

Reason: Getting this Error because apache image not available public Docker hub

[email protected] 63
Fix: To pull http image from public repository pull httpd image

5.11 Getting Error While Build


and run the application with
docker-compose Lab-14
Issue:

[email protected] 64
Reason: This error is coming because app.py file is wrong.

Fix: to fix this issue first


1. Instead of writing app.py file clone from our git using below command
$ git clone https://github.com/k21academyuk/docker

[email protected] 65
After this, follow the bellow steps.

1. Bring the application down


docker-compose down
2. Then Delete the Images created in

docker ps
docker images
and delete that image
Perform docker-compose up -d again

[email protected] 66
If you still getting this Error Please watch Session 200810 – CKA – Day 5 – Docker Compose &
Hands-on Lab with Docker File Day-5 in 2008 – [Weekday] Docker and Kubernetes (CKA) –
Live Recordings

URL: https://k21academy.com/topic/200810-cka-day-5-docker-compose-hands-on-lab-with-docker-file/

[email protected] 67
5.12 Unable to Docker Login or
Create a new Docker ID
Issue: azureuser@Test:~$ docker login
Login with your Docker ID to push and pull images from Docker Hub. If you don't have a Docker ID,
head over to https://hub.docker.com to create one.
Username: docker_id
Password:
Error saving credentials: error storing credentials - err: exit status 1, out: `Cannot autolaunch D-Bus
without X11 $DISPLAY`
azureuser@Test:~$

Reason: This would have happened because of a glitch in the process of Docker Installation.

Fix: Look into these two links from StackOverflow (shared below) if it still doesn't work out please
uninstall and reinstall docker to fix this issue.

Links - https://stackoverflow.com/questions/50151833/cannot-login-to-docker-account

https://stackoverflow.com/questions/51222996/docker-login-fails-on-a-server-with-no-x11-installed

5.13 Apache2 page not showing

Issue: I installed apache2 server on containers Vol-sharing1 and 2 and was trying to access the
page but i see nginx page and not apache2 page

Reason: This might be because of the indentation issues on your docker-compose.yml file.

[email protected] 68
Fix: Please fix the indentation issues in your file docker-compose.yml and this will fix your issue.

5.14 http://hostip:5000 -> This site


can’t be reached

Issue: "http://hostip:5000" I get the message "This site can’t be reached".. I opened up all ports

Reason: This might be because of browser cache memory.

Fix: Please clear the cache on your browser and this will solve your issue.

5.15 Web container is in exit state

Issue: Even after $ docker-compose up -d successfully the web container is is exited state.

$ docker-compose ps ------ stackdemo_web_1 is in exit status?


ubuntu@dockervm:~/stackdemo$ docker-compose ps
Name Command State Ports
----------------------------------------------------------------------
stackdemo_redis_1 docker-entrypoint.sh redis ... Up 6379/tcp
stackdemo_web_1 flask run Exit 1

Reason: This might be because of the indetation error.

Fix: Please make sure your docker-compose.yml indentation is proper, if not please fix it to
resolve this issue.

[email protected] 69
5.16 Runtime Error: invalid
memory address when doing
docker login
Issue: When running doker login facing below issue.

Reason: This error is due to the golang-docker-credential-helpers. Docker-compose requires


python-dockerpycreds, which in turn depends on golang-docker-credential-helpers. Therefore
executing docker login, while docker-compose is installed (more precisely golang-docker-
credential-helpers), as of now, won't work.
Reference: https://github.com/docker/cli/issues/2890
Fix: To fix this issue please uninstall docker-compose for now.

[email protected] 70
[email protected] 71
3. 17 EXTRA DOCKER QUESTION

Question: I am expected to install python I believe as the base image, with some of the steps included in
my original email, and at the end the output is suppose to give me the SHA1 value.
So after many tries, I was doing a stdin of the Dockerfile to a Dockerfile created using touch command. But
in the bash script, I 1st updated the system, installed docker, started docker, then created a Dockerfile with
the contents of the dockerfile standard input with command <<EOF. But I still didn't get the right output.
Answer:

[email protected] 72
3. 18 SUMMARY

In this activity Guide we learned:


• Docker Installation Steps on Ubuntu 18.04 server
• Working with Container
• Working with Docker Images
• Docker Private Registry
• Docker Default Bridge Networking
• Creating Custom Bridge Network
• Docker Host Network
• Docker Storage – Host Path Mounting
• Docker Volume
• Working with Dockerfile
• Working With Application Stack
• Configuring External DNS, Logging and Storage Driver

[email protected] 73

You might also like