Skip to content

Docker 🐳

Docker is a powerful containerization tool designed to simplify the process of creating, deploying, and running applications using containers. Containers package applications along with their dependencies, making it easy to deploy them consistently across different environments. Unlike traditional virtualization, containers share the host OS kernel, making them lightweight and efficient.

Installation of Docker Engine & Docker Compose on Ubuntu & CentOS πŸ“₯

To streamline the installation process, you can use the following script to install Docker Engine and Docker Compose on both Ubuntu and CentOS:

vim docker_setup.sh
Dockerfile
#!/bin/bash
apt --help >>/dev/null
if [ $? -eq 0 ]
   then 
echo " INSTALLING DOCKER IN UBUNTU"
echo
sudo apt update
sudo apt-get remove docker docker-engine docker.io containerd runc
sudo apt-get update
sudo apt-get -y install \
    apt-transport-https \
    ca-certificates \
    curl \
    gnupg \
    lsb-release
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
echo \
  "deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu \
  $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
sudo apt-get update
sudo apt-get install docker-ce docker-ce-cli containerd.io -y  
sudo docker run hello-world
    else
echo " INSTALLING DOCKER IN CENTOS"
echo
sudo yum remove docker \
                  docker-client \
                  docker-client-latest \
                  docker-common \
                  docker-latest \
                  docker-latest-logrotate \
                  docker-logrotate \
                  docker-engine
sudo yum install -y yum-utils
sudo yum-config-manager \
    --add-repo \
    https://download.docker.com/linux/centos/docker-ce.repo
sudo yum install docker-ce docker-ce-cli containerd.io -y   
sudo systemctl start docker
sudo docker run hello-world
fi
echo " Installing Docker Compose"
sudo curl -L "https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
docker-compose --version
Now, grant execute permission to the script:
sudo chmod +x docker_setup.sh
Finally, run the script to install Docker and Docker Compose:
./docker_setup.sh

Docker Commands πŸš€

List All Images πŸ“‹

To display all locally stored Docker images, use the following command:

docker image ls

Build an Image πŸ› οΈ

To create an image from a Dockerfile in the current directory and assign a tag, utilize this command:

docker build -t <imagename>:<tag> 

Delete an Image πŸ—‘οΈ

Remove an image from the local image store using the following command:

docker image rm <imagename>:<tag>

Run a container in an interactive mode:

docker run -it <imagename>:<tag>

Run a container from the Image nginx:latest, name it "web," and expose port 5000 externally, mapped to port 80 inside the container in detached mode: ▢️

docker run --name web -d -p 5000:80 nginx:latest

Run a detached container in a previously created container network: 🌐

docker network create <mynetwork>
docker run --name web -d --net mynetwork -p 5000:80 nginx:latest

Follow the logs of a specific container:

docker logs -f <container name or container container-id>

List only active containers 🟒

docker ps

List all containers πŸŸ’πŸ”΄

docker ps -a

Stop a container ⏹️

docker stop <container name or container container-id>

Stop a container (timeout = 1 second)

docker stop -t1

Remove a stopped container πŸ—‘οΈ

docker rm <container name or container container-id>

Force stop and remove a container

docker rm -f <container name or container container-id>

Remove all containers

docker rm -f $(docker ps-aq)

Remove all stopped containers

docker rm $(docker ps -q -f β€œstatus=exited”)

Execute a new process in an existing container: Execute and access bash inside a container

docker exec -it <container name or container-id> bash
To inspect the container
docker inspect <container name or container container-id>

To Establish Connections from Local to Remote. log in with your Dockerhub Credentials.

docker login
Pull an image from a registry

docker pull <imagename>:<tag>

Retag a local image with a new image name and tag

docker tag myimage:1.0 myrepo/myimage:2.0

Push an image to a registry.

docker push myrepo/myimage:2.0

Dockerfile πŸ“‹

  • 🏁 FROM - Base Image to run other instructions or commands

  • πŸƒβ€β™‚οΈ RUN - Run commands

  • πŸ“‚ WORKDIR - Set working directory in the container

  • πŸ“œ CMD - Command to run within the container

  • πŸ”‘ ENTRYPOINT - Configures a command that will run as the container starts, overriding the CMD instruction if both are specified.

  • πŸ“¦ VOLUME - Mount a directory from the host to the container

  • πŸ“ COPY - Copy files or directories to the container

  • βž• ADD - Copy files or directories to the container with additional features (like extracting TAR files)

  • 🏷️ LABEL - Add metadata to the image

  • 🌐 EXPOSE - Expose a port to enable network access to the container

Sample Dockerfile for Deploying a Static website.

vim Dockerfile
# Use the CentOS 7 base image
FROM centos:7

# Set metadata labels
LABEL "Author"="saiteja Irrinki"
LABEL "Project"="Wave"

# Install necessary packages - Apache, wget, and unzip
RUN yum install httpd wget unzip -y

# Download the website template
RUN wget https://www.tooplate.com/zip-templates/2121_wave_cafe.zip

# Unzip the downloaded template
RUN unzip 2121_wave_cafe.zip

# Copy the contents of the unzipped template to the web server directory
RUN cp -r 2121_wave_cafe/* /var/www/html/

# Start the Apache web server in the foreground
CMD ["/usr/sbin/httpd", "-D", "FOREGROUND"]

# Expose port 80 for web traffic
EXPOSE 80

# Set the working directory to the web server directory
WORKDIR /var/www/html

# Create a volume for Apache's log files
VOLUME /var/log/httpd

Using Variables in Dockerfile for Deploying a Static website.

vim Dockerfile
# Define variables
ARG AUTHOR="saiteja Irrinki"
ARG PROJECT="Highway"
# Use the variables
FROM centos:7
LABEL "Author"="$AUTHOR"
LABEL "Project"="$PROJECT"
RUN yum install httpd wget unzip -y

# Use --no-check-certificate flag to bypass SSL certificate checks
ARG DOWNLOAD_URL="https://templatemo.com/tm-zip-files-2020/templatemo_520_highway.zip"
RUN wget "$DOWNLOAD_URL" --no-check-certificate
ARG FILE="templatemo_520_highway"
RUN unzip "$FILE".zip
RUN cp -r "$FILE"/* /var/www/html/
CMD ["/usr/sbin/httpd", "-D", "FOREGROUND"]
EXPOSE 80
WORKDIR /var/www/html
VOLUME /var/log/httpd

# Set the image name and optionally a tag
LABEL "name"="$PROJECT"

vim Dockerfile
Adding Existing zip/tar files in Dockerfile

Docker expects the wave.tar.gz file to exist in the same directory where you are executing the docker build command. Docker will then copy the contents of that file into the /var/www/html/ directory within the Docker image being built.

# Use the latest Ubuntu base image
FROM ubuntu:latest

# Set metadata labels for author and project
LABEL "Author"="Saiteja Irrinki"
LABEL "Project"="Wave"

# Set environment variable to make the installation non-interactive
ENV DEBIAN_FRONTEND=noninteractive

# Update package list and install Apache2 and Git
RUN apt update && apt install apache2 git -y

# Add the contents of 'wave.tar.gz' to the Apache web server
# You can use either 'COPY' or 'ADD'. Here, we're using 'ADD'.
ADD wave.tar.gz /var/www/html/

# Start the Apache2 web server in the foreground
CMD ["/usr/sbin/apache2ctl", "-D", "FOREGROUND"]

# Expose port 80 for web traffic
EXPOSE 80

# Set the working directory to the Apache web server's document root
WORKDIR /var/www/html

# Create a volume for Apache2 log files
VOLUME /var/log/apache2

Build the image from the Docker file πŸ–ΌοΈ

Replace saitejairrinki/wavecafe:v1 with your preferred image name and tag.

 docker build -t saitejairrinki/wavecafe:v1 . 

Run Container From the Image πŸ“¦

docker run --name wavecafe -d -p 9699:80 saitejairrinki/wavecafe:v1
Access it from your browser, ensuring that you have allowed port 9699 (or your chosen port) in your security group if you are using a cloud VM. 🌐
Public-IPaddress:9699

Docker Image

You can pull my image and start a container from it without needing to create a Dockerfile.

docker pull saitejairrinki/wavecafe:v1

docker run --name wavecafe -d -p 9999:80 saitejairrinki/wavecafe:v1
Now Access From the Browser, Make sure you have to allow the port number in my case 9999 in your security group if you are using cloud VM.
Public-IPaddress:9999

Docker Compose πŸ“Ÿ

Creating Docker Compose for a single local Docker File

docker-compose.yml
version: "3"
services:
    Wavecafe:
        build:
            context: /Dockerfile_path/
        ports:
                - "5555:80"
        container_name: wavecafe

Creating Docker Compose for a Multi local Docker File

docker-compose.yml
version: '3'

services:
  website1:
    build:
      context: /home   # Path to the first Dockerfile directory
    ports:
      - "8081:80"      # Map port 8081 on the host to port 80 in the container

  website2:
    build:
      context: /tmp    # Path to the second Dockerfile directory
    ports:
      - "8082:80"      # Map port 8082 on the host to port 80 in the container

If you have multiple Dockerfiles in the same build context directory, you can use the dockerfile option to specify a different Dockerfile name.

docker-compose.yml
version: '3'

services:
  website1:
    build:
      context: ./website1
      dockerfile: Dockerfile1
    ports:
      - "8080:80"  # Map host port 8080 to container port 80

  website2:
    build:
      context: ./website2
      dockerfile: Dockerfile2
    ports:
      - "8081:80"  # Map host port 8081 to container port 80

Creating Docker Compose for DockerHub Images

docker-compose.yml
version: '3'
services:
  website:
    image: saitejairrinki/wavecafe:v1
    ports:
      - "8085:80"
docker-compose.yml
version: '3'
services:
  nginx:
    image: nginx
    ports:
      - "8085:80"
  wavecafe:
    image: saitejairrinki/wavecafe:v1
    ports:
      - "8086:80"

Start all containers defined in the docker-compose.yml file

docker-compose up

Start containers in the background (detached mode)

docker-compose up -d
Build or rebuild images and Start containers in the background (detached mode)
docker-compose up -d --build

Stop and remove all containers defined in the docker-compose.yml file

docker-compose down
Stop, remove containers, and remove volumes
docker-compose down -v

List containers and their current status

docker-compose ps

View logs of all containers defined in the docker-compose.yml file

docker-compose logs
Follow logs in real-time
docker-compose logs -f

Build or rebuild Docker images for all services

docker-compose build

Pull the latest images for all services

docker-compose pull

Restart all containers

docker-compose restart

Execute a command in a running container

docker-compose exec <service-name> <command>

Stop all containers without removing them

docker-compose stop

Start stopped containers

docker-compose start

Stop and remove containers, networks, volumes, and associated Docker images

docker-compose down --rmi all

Remove containers for services not defined in the docker-compose.yml file

docker-compose down --remove-orphans

Creating a Separate Directory to Store Container data

mkdir mountbind
Now link your Directory while running the container
docker run --name db01 -e MYSQL_ROOT_PASSWORD=secret123 -p 3300:3306 -v /root/mountbind:/var/lib/mysql -d mysql:5.7
Now do ls to the Directory there you can see the containers data
ls mountbind
Creating docker Volume, use the below command to see all the available options of docker volume
docker volume --help
Creating a new docker volume with name datadb
docker volume create datadb
Command removes all Docker volumes that are present on your system.
docker volume rm $(docker volume ls -q)
Now run your container with that volume
docker run --name db02 -e MYSQL_ROOT_PASSWORD=secret123 -p 3301:3306 -v datadb:/var/lib/mysql -d mysql:5.7
Now check
ls /var/lib/docker/volumes/datadb/_data/
Now for testing Create any file with any name of your choice, here I'm creating a file with the name Milkyway
touch /var/lib/docker/volumes/datadb/_data/milkyway
Now log in into the container and Verify your file.
docker exec -it db02 /bin/bash
ls /var/lib/mysql/
Now exit from the container
exit
If you want to access the MySQL database with a MySQL client then follow the below steps

sudo apt update
sudo apt install mysql-client
Now fetch the container IP by doing Docker Inspect
docker inspect db02 |grep -i ipaddress
Now Connect with that IP
mysql -h 172.17.0.4 -u root -psecret123