Tag Archives: Docker

Docker compose example

Introduction

Docker compose is used to run multiple containers. In this tutorial, Using Docker compose example for NGINX and MYSQL. I used Docker compose version “3”

In today’s digital era, Docker has become an essential tool for developers and DevOps professionals. With its ability to package and deploy applications easily, Docker has revolutionized the way software is managed and deployed. However, as applications grow more complex, managing multiple containers simultaneously can be challenging. This is where Docker Compose shines. This article will guide you through Docker Compose with a practical example, making it easier to manage and coordinate multiple containers within the same application.

“Build, Manage and Secure Your Apps Anywhere. Your Way.” Quote from docker!

Docker compose example

Creating Docker-compose file. All docker compose file is a YAML file. Now, let’s go create the docker-compose.yml file as below

[root@DevopsRoles ~]# mkdir docker-instance
[root@DevopsRoles ~]# cd docker-instance/
[root@DevopsRoles docker-instance]# vim docker-compose.yml

The content docker-compose file as below

version: '3'

services:
 WEB01:
   image: nginx:latest
   container_name: "web01"
   hostname: web01
   ports:
        - "8888:80"
        - "8443:443"
        - "2233:22"
   #deploy:
   # resources:
   # limits:
   # memory: 512M
   #mem_limit: 512m
   volumes:
     - ./data_web01:/mnt_nfs
   networks:
     - bridge
   restart: always

 DB01:
   image: mysql:latest
   container_name: "db01"
   hostname: db01
   ports:
        - "33306:3306"
        - "2234:22"
   command: --default-authentication-plugin=mysql_native_password
   environment:
      MYSQL_ROOT_PASSWORD: 123456789
      #MYSQL_USER=huupv
      #MYSQL_PASSWORD=passforhuupv
      #MYSQL_DATABASE=DevopsRolesDB
   #deploy:
   # resources:
   #    limits:
   #      memory: 512M
   volumes:
      - ./data_db01:/mnt_nfs
   networks:
      - bridge
   restart: always

volumes:
   web_mnt_nfs:
     driver: local
networks:
   bridge:
     driver: bridge
     ipam:
       config:
          - subnet: 192.168.12.0/24

Creating and starting a container

[root@DevopsRoles docker-instance]# docker-compose up -d

The screen output terminal:

Creating network "docker-instance_bridge" with driver "bridge"
Creating db01 ... done
Creating web01 ... done

The result, Docker compose example

Access browser Nginx server

Checking running containers for nginx and mysql

Conclusion

Thought the article, you can use “Docker compose example” as above. Docker Compose is not just a convenient tool but also a key to simplifying and enhancing container management in any software project. Continue reading the article to gain a deeper understanding of how to use this tool in real-world scenarios! I hope will this your helpful. Thank you for reading the DevopsRoles page!

Docker SSH into Container: A Complete Guide for Beginners and Advanced Users

Introduction

Docker containers have revolutionized the way developers build, ship, and manage applications. However, one common question arises: How do you Docker SSH into Container? While Docker doesn’t support traditional SSH access like physical servers, it provides a powerful alternative with the docker exec command. In this guide, we’ll explore step-by-step instructions on how to “SSH” into Docker containers from basic operations to more advanced use cases.

What is Docker SSH into Container?

Before diving into the practical steps, it’s important to clarify that Docker doesn’t actually use SSH for container access. Instead, Docker uses the docker exec command, which allows you to run commands or get an interactive shell inside running containers. This method is more efficient, secure, and tailored for containers than traditional SSH.

Why You Shouldn’t Use SSH for Docker Containers

  • Containers are lightweight: Adding an SSH server increases container size.
  • Docker has built-in tools: Using docker exec provides direct and simple access to containers without the overhead of SSH configuration.
  • Security: Running an SSH service in every container increases the attack surface. Docker’s approach with docker exec is more secure.

How to SSH into a Docker Container: Basic Method

Let’s start with the basics – getting into the shell of a running Docker container.

Step 1: List Running Containers

To view the currently running containers, you can use the following command:

docker ps

This command will display:

  • CONTAINER ID: Unique ID for each running container
  • IMAGE: The Docker image used to create the container
  • COMMAND: The main process running in the container
  • STATUS: Whether the container is running, paused, or stopped
  • NAMES: Friendly names assigned to containers for easy identification

Step 2: Access the Shell of a Running Container

Once you have the container ID or name, you can use the docker exec command to access the container’s bash shell. For example:

docker exec -it <container_ID_or_name> /bin/bash
  • -i: Keep STDIN open even if not attached.
  • -t: Allocate a pseudo-TTY, allowing you to interact with the container.

If your container uses a different shell, such as sh, replace /bin/bash with the appropriate shell path.

Advanced Docker Exec Usage

Once you’ve mastered the basics, you can use the docker exec command for more advanced tasks. Let’s look at some examples.

Running Commands in a Docker Container

You don’t always need to access a full shell; sometimes you just need to run a single command. You can do this using the docker exec command, followed by the command you want to execute. For example, to check the /etc/hosts file inside a container:

docker exec -it <container_ID_or_name> cat /etc/hosts

Inspect Container Configuration

To view detailed information about a container, such as its environment variables, network settings, and mounted volumes, use:

docker inspect <container_ID_or_name>

This is helpful when you need to troubleshoot or validate container configurations.

How to SSH into Stopped or Exited Containers

You can only run the docker exec command on running containers. If your container has stopped or exited, you need to start it before you can access it. Here’s how:

  1. List all containers (including stopped ones):
docker ps -a
  1. Start a stopped container:
docker start <container_ID_or_name>
  1. SSH into the container using the previously mentioned docker exec command.

Automating Docker SSH Access

For users who frequently need to access containers, creating a function in your .bashrc or .zshrc file can streamline the process:

function docker_ssh() {
    docker exec -it $1 /bin/bash
}

This allows you to use a simpler command like docker_ssh <container_ID_or_name>.

Frequently Asked Questions (FAQs)

1. Can I install SSH in a Docker container?

Yes, you can install SSH in a Docker container, but it’s generally discouraged. Adding SSH increases the container’s size and complexity. Using docker exec is the recommended way to access containers.

2. How do I copy files between my host machine and Docker containers?

You can use the docker cp command to copy files from your host to the container or vice versa. For example:

docker cp <source_path> <container_ID_or_name>:<destination_path>

3. How can I access Docker containers with graphical applications?

Docker containers can run graphical applications using X11 forwarding, but this setup requires additional configuration beyond simple terminal access.

4. What happens if I stop a container after SSHing into it?

If you stop a container while you’re connected using docker exec, your session will end immediately. You must restart the container to regain access.

Advanced Topics: Managing Multiple Containers

In environments with many running containers, it’s essential to efficiently manage them. Here are a few strategies:

Using Docker Compose for Multi-Container Applications

If you are running multiple containers, Docker Compose is a valuable tool. It allows you to define and manage multi-container applications with a simple YAML configuration file. To install and use Docker Compose:

sudo apt-get install docker-compose
docker-compose up

With Docker Compose, you can specify the configuration for all containers in one place, making it easier to scale, start, and stop services together.

Handling Docker Networks

Managing container networks is crucial, especially for multi-container applications. Docker provides default networking, but you can create custom networks for better isolation and performance.

  • List networks: docker network ls
  • Create a new network: docker network create my_network
  • Run a container on a network: docker run --network my_network <image>

Conclusion

Accessing a Docker container’s shell or executing commands inside it is made simple with the docker exec command. This guide covered everything from basic shell access to running advanced commands and managing multiple containers. Docker’s flexibility allows you to streamline container management without the need for traditional SSH. Thank you for reading the DevopsRoles page!

How to inspect Docker container

Introduction

In this tutorial, I’ll guide you on How to inspect docker container to gain detailed insights into containers. Docker inspect is a powerful tool that provides comprehensive information about various aspects of a container, including its network settings, current status, attached volumes, and more. By exploring these details, you’ll have a deeper understanding of your containers’ configurations and runtime characteristics.

This knowledge proves invaluable for troubleshooting, optimization, and gaining a holistic view of your Dockerized applications. Follow along as I demonstrate the versatility of Docker inspect, enabling you to effectively manage and analyze your containers with precision and ease.

What is docker inspect?

Docker inspect ” is a command in Docker that provides a detailed overview of container information. This powerful tool unveils specifics such as network configurations, status, and attached volumes. By leveraging “docker inspect,” users gain valuable insights into container settings and runtime details, essential for troubleshooting and optimizing Dockerized applications. Mastery of this command empowers efficient container management, allowing users to delve into the intricacies of their Docker environments with precision and ease

What is a Docker container?

  • Portable Packages: Docker containers encapsulate applications along with their dependencies, ensuring a consistent and portable environment.
  • Isolation: Containers operate independently, isolated from the host system and other containers, promoting stability and consistency.
  • Comprehensive Inclusion: Each container includes the necessary components—code, runtime, libraries, and tools—creating a self-contained unit ready to execute.
  • Docker Platform: Docker, a widely used containerization platform, facilitates the seamless packaging and deployment of applications.
  • Cross-Environment Consistency: Developers can build a container once and run it consistently across various environments, from local development setups to large-scale production systems.
  • Resource Efficiency: Containers optimize resource utilization, offering agility, scalability, and quick deployment, making them popular in modern software development and deployment practices.

Inspect Docker container

Utilize the “docker ps” command to showcase a list of containers as follows:

$ sudo docker ps

The displayed results below

CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
055772699b49 devopsroles/nginx:v2 "nginx" 4 seconds ago Up 2 seconds 0.0.0.0:8080->80/tcp devopsroles

Provide details for the “devopsroles” container as illustrated below:

$ sudo docker inspect devopsroles

As an illustration, the output for the “devopsroles” container is presented below:

The omit
"NetworkSettings": {
 "Bridge": "",
 "SandboxID": "38a0b8ae70f0853cf36b25add2182132c2b31183c3d969f7c2b927f75080288c",
 "HairpinMode": false,
 "LinkLocalIPv6Address": "",
 "LinkLocalIPv6PrefixLen": 0,
 "Ports": {
 "80/tcp": [
 {
 "HostIp": "0.0.0.0",
 "HostPort": "8080"
 }
 ]

},
 "SandboxKey": "/var/run/docker/netns/38a0b8ae70f0",
 "SecondaryIPAddresses": null,
 "SecondaryIPv6Addresses": null,
 "EndpointID": "c0103fac129e8ff88fcb597b6cfd1836ca7ffb50580cbe60dc6e7b39f2de1e24",
 "Gateway": "172.17.0.1",
 "GlobalIPv6Address": "",
 "GlobalIPv6PrefixLen": 0,
 "IPAddress": "172.17.0.2",
 "IPPrefixLen": 16,
 "IPv6Gateway": "",
 "MacAddress": "02:42:ac:11:00:02",
 "Networks": {
 "bridge": {
 "IPAMConfig": null,
 "Links": null,
 "Aliases": null,
 "NetworkID": "42dd4e0f69e1edff2c81b2f311b2a0ed53478f47fdf5371643df9f1bdb150ba5",
 "EndpointID": "c0103fac129e8ff88fcb597b6cfd1836ca7ffb50580cbe60dc6e7b39f2de1e24",
 "Gateway": "172.17.0.1",
 "IPAddr$ sudo docker inspect devopsrolesess": "172.17.0.2",
 "IPPrefixLen": 16,
 "IPv6Gateway": "",
 "GlobalIPv6Address": "",
 "GlobalIPv6PrefixLen": 0,
 "MacAddress": "02:42:ac:11:00:02"
 }
 }

How to display the IP Address for the “devopsroles” container as below:

$ sudo docker inspect -f '{{ .NetworkSettings.IPAddress }}' devopsroles

Below is the presented output:

172.17.0.2

For example, display IP, Image, Name, Host Config, and status for containers as below:

$ sudo docker inspect -f 'Image:[{{ .Config.Image}}] Name:{{.Name}} HostConfig:{{ .HostConfig.Binds}} Status:{{ .State.Status}} IP_Container:{{ .NetworkSettings.IPAddress }} ' 055772699b49 | cat -n

The output below:

1 Image:[devopsroles/nginx:v2] Name:/devopsroles HostConfig:[/home/huupv/project/nginx/devopsroles:/var/www/html/devopsroles:ro] Status:running IP_Container:172.17.0.2

An alternative approach is as follows:

$ sudo docker inspect -f 'Image:[{{ .Config.Image}}] Name:{{.Name}} HostConfig:{{ .HostConfig.Binds}} Status:{{ .State.Status}} IP_Container:{{ .NetworkSettings.IPAddress }} ' $(sudo docker ps -a -q) | cat -n

How to display all containers, including non-running

$ sudo docker ps -a -q

The output below:

055772699b49

Conclusion

Throughout the article, we guide you on inspecting containers effectively. Learn how to determine crucial container details such as status, volume, and networking. We’ll continually update this post with useful commands for your reference. Thank you for exploring the DevopsRoles page – we appreciate your readership!

Docker build image from Dockerfile

Introduction

Creating our own Docker images starts with a Dockerfile. Using the docker build command, we can easily transform the instructions in the Dockerfile into a new image. Wondering How to Docker build image from Dockerfile? Let’s dive in!

The first images built with Docker

To create a directory and a Dockerfile, the sample as below:

$ mkdir project
$ cd project
$ touch Dockerfile

The example Docker build the image from Dockerfile

$ vim Dockerfile

The content a Dockerfile as below:

 # CentOS 7 Dockerfile
 # Docker build:
 # sudo docker build -t devopsroles/centos:latest .
 # Docker create:
 # sudo docker create -it --name centos -h centos devopsroles/centos
 # Docker start:
 # sudo docker start centos
 # Connect with bash
 # sudo docker exec -it centos bash
 FROM centos:latest
 MAINTAINER PHAN VAN HUU <pvhuu90@gmail.com> My blogs: devopsroles.com
 #Update centos
 RUN yum update -y && yum upgrade -y
 RUN yum -y install git curl net-tools wget vim
 # Install EPEL Repository
 RUN yum install -y epel-release
 # Clean CentOS 7
 RUN yum clean all
 # Set the environment variables
 ENV HOME /root
 # Working directory
 WORKDIR /root
 # Default command
 CMD ["bash"]

Docker build image from Dockerfile

Running the Dockerfile use Docker build commands

$ cd project
$ sudo docker build -t .
$ sudo docker build -t devopsroles/centos:latest .
$ sudo docker create -it --name centos -h centos devopsroles/centos

The result, Docker images devopsroles/centos as below:

$ sudo docker images

The output, docker images as below:

 REPOSITORY TAG IMAGE ID CREATED SIZE
 devopsroles/centos latest c9ef43af9836 2 minutes ago 428.7 MB

The docker start container centos

$ sudo docker start centos
$ sudo docker ps

The output below:

CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
 2d1a8e53668f devopsroles/centos "bash" 43 seconds ago Up 4 seconds centos

The connect container bash

$ sudo docker exec -it centos bash

The output below:

[root@centos ~]# ifconfig
 eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
 inet 172.17.0.2 netmask 255.255.0.0 broadcast 0.0.0.0
 inet6 fe80::42:acff:fe11:2 prefixlen 64 scopeid 0x20<link>
 ether 02:42:ac:11:00:02 txqueuelen 0 (Ethernet)
 RX packets 8 bytes 648 (648.0 B)
 RX errors 0 dropped 0 overruns 0 frame 0
 TX packets 8 bytes 648 (648.0 B)
 TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
 inet 127.0.0.1 netmask 255.0.0.0
 inet6 ::1 prefixlen 128 scopeid 0x10<host>
 loop txqueuelen 1 (Local Loopback)
 RX packets 0 bytes 0 (0.0 B)
 RX errors 0 dropped 0 overruns 0 frame 0
 TX packets 0 bytes 0 (0.0 B)
 TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

[root@centos ~]# ping 8.8.8.8
 PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
 64 bytes from 8.8.8.8: icmp_seq=1 ttl=127 time=68.7 ms
 64 bytes from 8.8.8.8: icmp_seq=2 ttl=127 time=69.1 ms
 ^C
 --- 8.8.8.8 ping statistics ---
 2 packets transmitted, 2 received, 0% packet loss, time 1001ms
 rtt min/avg/max/mdev = 68.720/68.945/69.170/0.225 ms

Or test ping 8.8.8.8 from docker run command as below

$ sudo docker run centos ping 8.8.8.8 -c4

The output below:

 PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
 64 bytes from 8.8.8.8: icmp_seq=1 ttl=127 time=40.6 ms
 64 bytes from 8.8.8.8: icmp_seq=2 ttl=127 time=41.7 ms
 64 bytes from 8.8.8.8: icmp_seq=3 ttl=127 time=42.1 ms
 64 bytes from 8.8.8.8: icmp_seq=4 ttl=127 time=40.1 ms

--- 8.8.8.8 ping statistics ---
 4 packets transmitted, 4 received, 0% packet loss, time 3005ms
 rtt min/avg/max/mdev = 40.124/41.184/42.196/0.832 ms

Conclusion

Docker build image from Dockerfile. You can update and edit package from Dockerfile file. For example to install Nginx, PHP, MySQL package in Dockerfile file. Thank you for reading the DevopsRoles page!