iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🐡

Getting Started with Docker Again

に公開
2023/10/11

Introduction to Docker for Beginners

Introduction

Starting with devcontainers, using containers when building development environments has become common practice.
However, in reality, I don't really understand containers well.
I'm in a state where I just copy and paste code I find online and consider myself lucky if it works.
I felt this wasn't right and wanted to at least be able to explain what the copy-pasted code is intended to do.
Therefore, in this article, I would like to use Docker to briefly learn the overview of container technology.
Please note that I have not included instructions for installing Docker.
Please install it separately.
Additionally, I am using Docker on WSL2, and my Docker version is 20.10.21.
I really should update it soon.
Well then, let's begin.

About Container Characteristics: One Step Before the Basics of Basics

① Independent and Lightweight Execution Environments

In the past, virtual machines were used to create independent environments.
While independent execution environments can certainly be created this way, it is necessary to build an OS for each environment.
Consequently, high resource consumption was a significant disadvantage.
On the other hand, a container does not include an OS kernel itself.
Quoted from What is a Virtual Environment (VMware)? Explaining the Mechanism, Pros, and Cons
Quoted from What is a Virtual Environment (VMware)? Explaining the Mechanism, Pros, and Cons
This is because the container itself is part of a process.
However, the process generating the container uses Host OS features to provide stronger isolation than a normal process, allowing for the construction of an independent environment.
The above is a very brief overview of why containers are lightweight and how they maintain independence.
Now that we understand the concept, let's actually see how each container is independent and does not affect others.
First, we use the docker run -it --name mycontainer1 ubuntu command* to create a container named mycontainer1.
*Note: Simply installing Docker is not enough to create a container with this command. Details on how to run containers will be provided later, so for now, please just understand that a container named "mycontainer1" has been created.
Next, create a container named mycontainer2 using the docker run -it --name mycontainer2 ubuntu command.
When these are executed, a bash shell will start. In the mycontainer1 container, execute the command echo "test" > /test.txt and confirm that the file exists.
2023-09-02_15h12_40.png
Meanwhile, if you try to call the test.txt file in the mycontainer2 container, an error will be displayed stating that the file does not exist.
2023-09-02_15h14_49.png
From the above, we can see that each container exists independently.
Maintaining independence allows for easy environment construction without depending on the specific PC (though environment construction still remains one of the most difficult challenges...).

② High Portability

Images, which are the source of containers, are very easy to distribute.
This is because, in addition to the independence and lightweight nature of containers, tools surrounding containers like Docker and Kubernetes are well-developed, making them easy to use at the distribution destination.
This ease of distribution and the existence of many tools to reproduce the environment at the destination are cited as advantages of containers.

③ Ecosystem

Containers are a widely used technology in infrastructure, and there are a considerable number of tools and OSS related to containers.
Furthermore, there are projects like the Open Container Initiative (OCI) that establish standard specifications for containers, and the Cloud Native Computing Foundation (CNCF), which determines the maturity of OSS projects.
The abundance of information related to containers, as mentioned above, is also one of the characteristics of container technology.
Having touched upon the characteristics of containers very briefly, from here on, we will use Docker—which is widely used for handling containers—to explore various aspects of the container environment.

Getting Hands-on with Docker

Actually Running a Docker Container

docker pull command
The pull command is used to retrieve Docker images.
It is similar to the git pull command used when fetching code from GitLab or GitHub.
We are retrieving the group of files for the Docker container we are about to run using the pull command.
Let's try pulling the ubuntu image this time.
Run the command docker pull ubuntu in your terminal.
If a message like "Status: Downloaded newer image for ubuntu:latest" is displayed near the end, the image has been downloaded correctly.
Now, let's check the details of the image.
When performing operations on images, we use the docker images command.
First, let's check the images existing in our own environment with docker image -a.
2023-09-02_10h11_53.png
A display like the one above will appear.
Let's look at each item.

  • REPOSITORY
    • The name of the image.
  • TAG
    • The tag for the image.
    • Often used to indicate the version of the image.
  • IMAGE ID
    • The ID assigned to the image.
    • You use this ID when specifying an image.
  • CREATED
    • Indicates the time the image was created in your environment.
  • SIZE
    • The data size of the image.
      Even though it hasn't been containerized yet, it's surprising that the size of ubuntu, which is a Linux OS, is only about 77MB.
      I felt a bit of the reason why Docker is said to be lightweight.

Side Note: Where are Docker images stored?

When you want to retrieve an image from Docker, you use the docker pull command. These images are stored in a service called Docker Hub, which is a Docker image sharing service.
Therefore, if you want to know the details of an image, such as which version exists or which image is appropriate for your Linux environment, it is best to refer to this site.
As an example, please take a quick look at the Docker image for MySQL.
You can find various information such as the commands for pulling the image, versions, and how to start the container.
In this way, if you want to run a container equipped with the app or functionality you need, you will search for it on Docker Hub, refer to the documentation, and execute the command.
However, there is one thing to be careful about.
Anyone can upload an image to Docker Hub as long as they create an account.
Therefore, there is a possibility that unmaintained images or even malicious images have been uploaded.
That said, it is difficult for a Docker beginner to look inside an image and judge whether there is a problem.
In such cases, a helpful guide for deciding whether it is safe to pull an image is the presence of the "Docker Official Image" badge.
If you check the Docker image for MySQL page again, you will see a badge labeled "Docker Official Image" next to the image name.
2023-09-02_09h51_19.png
This is granted by Docker Inc. to images whose contents and documentation have been verified, and for which accuracy and regular updates are guaranteed.
The presence of this badge means the image has been endorsed by Docker Inc. as a legitimate image.
For Docker beginners like me who cannot judge the pros and cons of an image, pulling an image with the "Docker Official Image" badge significantly reduces the risk of accidents.
Until you get used to Docker, try to use only images that have the "Docker Official Image" badge.
--- End of Side Note ---

Up to this point, we have successfully retrieved an image into our own environment.
However, as with git, when you actually run an app, you would normally execute some command to start the server.
The same applies to Docker.
To start an image as a container, you need to execute a separate command.
That is the docker run command.
By executing the docker run command, you can start the image as a container and run the applications included in that image.
Let's actually start it.
Execute the command docker run -it ubuntu.
By the way, you can also start a container using the Image ID with a command like docker run -it c6b84b685f35.
When you execute the command, a bash shell should start, looking something like root@8e7f2480c9b7:/#.

Side Note: About the -it Option

If you don't include the -it option, the container will start and immediately exit without displaying anything. This is because the -it option stands for standard input (i.e., accepting input from the keyboard) and standard output (i.e., launching the bash shell). By specifying these options and starting the container, the bash shell will be displayed as shown earlier, allowing you to enter commands.

In addition to these options, you can specify commands to be executed when the container starts or assign tags. However, I only remember using them when setting up a study environment, so I will omit them here. I will touch on these options indirectly later when discussing Docker Compose.
--- End of Side Note ---

Once the bash shell is open, open another terminal and check the status of the container. To check the status of a container, use the docker ps command. You will see a result like the image below.

2023-09-02_11h35_10.png

If the STATUS part says "Up 5 seconds" (a display starting with "Up"), the container has successfully started. Other display details are as follows:

  • CONTAINER ID
    • The ID assigned to the container.
    • Specify this ID when deleting the container, etc.
  • IMAGE
    • The name of the image the container is based on.
  • COMMAND
    • The command specified when starting the container.
    • The container ends when this command finishes.
  • CREATED
    • The time the container was created.
  • STATUS
    • The status of the container.
    • There are multiple states, such as "Up" when running and "Exit" when it has finished.
  • NAMES
    • The name of the container.
    • If no name is specified, a name in the format "adjective_personname" is assigned.

Additionally, the docker ps command has the -a option to display the status of all containers (including running and stopped ones), the -q option to display only container IDs, and the -l option to show information about the last created container. Please use these as needed when you want to check the status of your containers.

Now that we have confirmed the container is running, we will proceed to delete it. The reason for deleting containers is that they consume space if left running. Look at the following image:

2023-09-02_10h57_12.png

This is the result of running the docker ps --size command in another terminal while the ubuntu container is running. I want you to pay attention to the SIZE section. Checking the SIZE, you can see that the ubuntu container is using 77.8MB of capacity.

It is written in a strange way as "0B(virtual 77.8Mb)," but for now, please just understand that the currently running ubuntu container is using 77.8MB of disk space. I will discuss the details in a later side note, so I'll skip it for now. Although containers are lightweight, if you keep a large number of them running, they will take up disk space. Therefore, it is better to delete containers you are not using.

So, let's delete the container. Execute exit inside the currently running ubuntu container to stop it. Now, I apologize for jumping ahead, but some of you might think that because the container is stopped, it doesn't affect the disk anymore. I thought so too. However, if you look at the list of stopped containers using the docker ps -a --size command:

2023-09-02_11h27_06.png

Disk allocation still exists even for stopped containers. In this way, simply stopping a container doesn't free up the space it occupies, so it is recommended to delete the container if you are not using it. To delete a container, use the docker rm command. Using the container ID "82f5e1b530c4" confirmed earlier, execute the docker rm 82f5e1b530c4 command. After it's done, nothing will be displayed even if you run the docker ps -a command. With this, the container deletion is complete.

By the way, if you want to delete all unused containers, you can do so by executing the docker container prune command. However, since it will also delete any data volume containers mentioned later, it's not something that should be used in every situation.

Side Note: About the container SIZE being expressed as "0B(virtual 77.8Mb)"

Earlier, when we checked the container size, something called "virtual" appeared that I didn't quite understand. First, let's look at what the documentation says about it.

  • size: The amount of data (on disk) that is used for the writable layer of each container.
  • virtual size: The amount of data used for the read-only image data used by the container plus the container's writable layer size. Multiple containers may share some or all of their read-only image data. Two containers created from the same image share 100% of their read-only data, while two containers with different images which have common layers in their heritage share those common layers. Therefore, you cannot just total the virtual size. This may overstate the total disk usage by a potentially non-trivial amount.

What does this mean? To put it simply without fear of being misunderstood, size refers to the capacity of the data I created inside the container, and virtual size is the value of the Docker image capacity plus the size value.

In "0B(virtual 77.8Mb)", 0B is the size value, and 77.8Mb is the virtual size value. Since the size of the ubuntu image downloaded earlier was 77.8MB and no data was created just by starting the container, the above understanding should be generally correct.

To be sure, let's create a dummy file of about 9MB with the command dd if=/dev/zero of=test9M bs=1M count=9. After that, checking the container capacity with the docker ps --size command, you can see that both size and virtual size have increased by about 9MB, as shown in the image below.

2023-09-02_14h41_05.png

There is also an answer for those who had similar questions in the GitHub issue, so please check it if you like. The above is an overview of "0B(virtual 77.8Mb)" displayed when checking the container size.

Now we know how to check how much capacity a single container is using. However, there is one point to be careful about. When calculating the total capacity used by multiple containers, you may not simply add the virtual values.

Containers have separate environments and do not affect other environments. As confirmed by the command earlier, changes in one container are not reflected in the other. On the other hand, containers are not completely isolated. The part consisting of the Docker image within the container is shared if the same Docker image is used. To get an idea of the image, look at the image below.

Quoted from What is the Layer Structure of Docker Containers?

Quoted from What is the Layer Structure of Docker Containers?

Docker is designed to reuse read-only file groups used to run the environment if the content is the same. This is to prevent unnecessary capacity usage if Docker image parts were created anew for each container. On the other hand, data newly created within a container is not shared, ensuring that unique parts of each container do not affect others.

To avoid breaking Docker's advantage of being lightweight, the foundation for running is kept the same for all containers, and only the essential parts are allowed to run uniquely. I was impressed by this technology, thinking "That's clever."

Putting a Simple App into Docker

We previously went through the process from starting to deleting an ubuntu container. Here, we will install ping into the ubuntu container so that the ping command can be executed. However, it's so simple that I hesitated whether to even make it a separate section.

First, start the ubuntu container with the docker run -it ubuntu command and enter the container. Then, update the repository with apt update and install ping with the apt install iputils-ping command. Once installed, run ping localhost and confirm that it works.

That's it. It's almost the same flow as doing it in a Linux environment like WSL2. The difference is that the shell inside the container is the root user, whereas normally you wouldn't operate as the root user. It's very convenient to be able to use ubuntu functions while being isolated from other environments. I feel again how amazing containers are.

Learning the Basics of Basics of Docker

Previously, we touched upon Docker centering on containers by starting and deleting them. However, Docker still has many more features. In this chapter, we will learn the basics of basics of Docker from the state of having finished a tutorial by touching on a few more of Docker's features.

Starting a Web Server

Here, we will introduce an Apache container and start a slightly more practical container. The goal is to run a web server and be able to display a web page.

First, obtain the official Apache image with the docker pull httpd command. Next, start the Apache container with the docker run -d httpd command. The -d option means starting in detached mode. Since Apache is a web server, it is required to be constantly running. Therefore, it is started in detached mode to run in the background. This ensures the server doesn't go down even if you accidentally close the terminal. Once you confirm that the container has been created with docker ps, the container startup is complete.

Now that the Apache server is running, let's immediately access http://localhost. Then, surprisingly, an error screen appears saying "This site could not be reached."
Is something wrong with the container?
Actually, there is no abnormality in the container. The container is running normally, and the Apache server is working fine inside the container. However, with the previous container startup method, browser access cannot reach the container.
When accessing http://localhost from a browser, the Host OS handles it first. Then, the Docker Engine on that Host OS judges which container to send the communication to based on the port number that received the access and collaborates with the container.

Quoted from Docker Practice: Adding Port Forwarding Settings to Access Docker Containers from Outside. Access was not possible because the red arrow in the image was not set.
Quoted from Docker Practice: Adding Port Forwarding Settings to Access Docker Containers from Outside. Access was not possible because the red arrow in the image was not set.

If you configure the above settings, accessing http://localhost in your browser will connect to the Apache server in the container. Now, let's go back to the previous docker run -d httpd command. The above command starts the container but does not specify the container's port number to connect to for the port number that the Host OS received access from in Docker Engine. Therefore, even if the container could be started, the browser could not connect to the Apache server.

Since we just need to specify the port number for the Docker Engine, we use the -p option when starting the container, like docker run -p 80:80 -d httpd, to link the port number received by the Host OS with the corresponding container port number. Please note that when specifying port numbers, the configuration is "Host OS port number:container port number." Now that the port number setting is complete, accessing http://localhost once again displays the familiar "It Works!"

2023-09-03_11h19_45.png

About Data Handling When Using Containers

As a philosophy of containers, there is a premise that containers themselves are disposable and should be discarded once their use is finished.
Therefore, storing data inside a container is not an appropriate method. If you leave data that you cannot afford to lose inside a container, you will no longer be able to treat the container as disposable.

However, there are often data types like logs that you don't want to lose. In this section, we will learn techniques for persistently saving such data while still using containers.

There are two ways to store data persistently:

  1. Save to a directory on the Host OS side outside of Docker's management.
  2. Create a dedicated data container called a "data volume container" and save it there.

We will look at each method, but before that, let's review "mounting," which Docker uses as a way to store data persistently.

About the Data Storage Method: "Mounting"

Mounting is a technology that integrates an area on a device different from the OS into the OS's directory hierarchy, making it accessible. To get a better idea, imagine plugging a USB drive into a computer.

2023-09-03_11h48_00.png

As shown in the image above, when you plug a USB memory stick into a Windows PC, a directory that allows access to the data inside the USB is displayed. This makes it possible to access the USB from the computer. Setting up a directory that serves as a connection point to access another device, such as a USB, is exactly what mounting is.

In this context, by creating a directory that serves as a connection point between the host OS (Linux) or a volume and the container, you will be able to retrieve previous data even if you delete the container and start it again. By the way, the connection point is called a "mount point," and the directory it connects to is called a "mount directory."

Now that we've touched upon mounting, let's look at how to actually store data persistently.

Saving to a Host OS-side Directory Outside of Docker's Management

Here, we will set the data storage location to the host OS outside the container so that the data remains. Since we were using Apache earlier, I'd like to say we'll save logs, but for now, I want to check quickly, so we will mount the DocumentRoot, which is the public directory at the top of the website.

First, in the Docker container, we set the DocumentRoot directory as the mount point. The default value for Apache's DocumentRoot directory is /usr/local/apache2/htdocs/, so we specify that. Next, we create the /root/webContents directory on the host OS side and mount these two folders.

Run the following commands in order on the host OS side to create an index.html file containing "hello world".

cd /root
mkdir webContents
cd webContents
echo "hello world" > index.html

Once created, you start the container, but you need to run it while mounting. The option used for this is the -v option. Mount by specifying "host-side directory:container-side directory" after this option.

Everything else is the same as described in "Starting a Web Server". Now, let's run the docker run -v /root/webContents/:/usr/local/apache2/htdocs -p 80:80 -d httpd command and try accessing http://localhost.

You will see that the content of the index.html file you created earlier in the webContents directory is reflected on the screen.

2023-09-03_12h37_31.png

In this way, by mounting a container directory to a host directory, the data remains even after the container is destroyed. However, this method of persisting data using the host OS is deprecated in Docker for the following two reasons:

  1. There is a possibility of unintended behavior due to differences in accounts and permissions between the Docker container and the host OS side.
  2. It results in dependency on the host OS environment, which hinders the independence that is a major advantage of Docker containers.

Because of these drawbacks, Dockerfiles do not allow mounting directories on the host OS side in the first place. Therefore, to persist data in a container, you should use data volumes or data volume containers (which are data volumes turned into containers), as explained next.

However, while outputting persistent data to a host OS directory is deprecated, it is common to save backups of Docker data volumes there. So, knowing about the interaction between the host OS and containers is still beneficial.

Persisting Data Using Data Volumes and Data Volume Containers

Here, we will perform data persistence using data volumes and data volume containers, which are data volumes turned into containers.

A data volume refers to an area for saving data.

Quoted from 【Docker】Part 6: About Mounting (volume)
【Docker】Part 6: About Mounting (volume) quoted from

Therefore, we first create a data volume and then mount the container to it. Note that if you share a single data volume across multiple containers, you use a data volume container.

Let's try creating a data volume.
Execute the docker volume create --name=datavolume command.
With this command, we have created a data volume.
Confirm that the created volume is displayed using docker volume ls.

2023-09-03_12h56_41.png

One important thing when creating a volume is to specify a volume name with the --name option. If you don't specify it, a random volume name will be assigned, which is inconvenient because you won't know the purpose of the volume when connecting from a container. Therefore, to understand the intention behind the volume's creation, it is best to specify a volume name using the --name option.

Now that the volume is created, let's start a container while setting up the mount. This time, we will start an ubuntu container and specify the /tmp directory as the mount point. Execute the command docker run -it -v datavolume:/tmp/ ubuntu to enter the container. Then, create a data.txt file in the tmp directory with the command touch /tmp/data.txt. Afterward, stop the container by executing exit and use the docker rm [Container ID] command to destroy the container. Normally, the data.txt file created in the tmp directory inside the container would disappear when the container is destroyed. However, since we are mounting it to a data volume this time, the data remains. To confirm this, execute docker run -it -v datavolume:/tmp/ ubuntu again to start the container. Once inside, running ls /tmp/ shows that the data.txt file created earlier is still there. In this way, data volumes persist regardless of container creation or destruction. Therefore, if you want to persist data, make sure to use data volumes. Now that we have successfully created and used a data volume, let's delete any volumes we no longer use, just as we do with containers. One point to note is that to delete a data volume, you must first delete any containers using that volume. Therefore, delete the volume using the docker volume rm [Volume Name] command after executing docker rm [Container ID]. This concludes the overview of data volumes and their creation and deletion.

Next, we will perform data persistence using a dedicated data container called a "data volume container." First, let's review data volumes once again.

Untitled

As we saw, these allow for data persistence by creating a storage area and mounting it to a container. Even with different containers, data can be retrieved as long as the mount destination is the same. However, if the mount path differs even slightly between containers, the data sharing destination changes, and you may not be able to retrieve the data as expected even when using the same volume.

To resolve this issue, we use data volume containers. A data volume container is a container that has been pre-mounted to a data volume, and other containers can interact with the volume data via the data volume container. Since the mount destination is already specified in the data volume container, there is no need to mount to the data volume for each container, which prevents mistakes in specifying the mount destination.

Quoted from 【Docker】Part 7: About Mounting (Data Volume Containers)
Quoted from 【Docker】Part 7: About Mounting (Data Volume Containers)

Let's try it right away.
First, create a data volume with the docker volume create --name=datavolume command.
Next, create a container that shares data with the data volume using the docker run --name=data-container -v datavolume:/tmp ubuntu command.
This container serves as the data volume container.
Therefore, we use the --name option to set a name for the container, making it easier to link with other containers.
To create a container linked to the data volume container, use the --volumes-from option.
So, by starting a container with the docker run --volumes-from data-container -it ubuntu command, you can now interact with the data volume via data-container.
To confirm that it is accessible from any container, execute another similar command and try creating a file in the mounted directory of each container.
You should be able to see that the data is shared between the containers.
With this, we have successfully created a data volume container.
While it might not feel that effective now when the number of containers is small, I think we'll reap the benefits as the number of containers increases in the future.
Note: If you are using a data volume container, be careful with the docker container prune command, which deletes containers that are not running.
Since a data volume container is always treated as being in a stopped state, executing the above command will also delete the data volume container.
Because only the container is deleted, it doesn't affect the data volume itself, and you can recover by creating a new data volume container with the same mount destination.
However, if you aren't aware of this, you might panic thinking you've lost all your data when the data volume container disappears due to the docker container prune command, so I'm sharing this here.

Backing Up and Restoring Data Volume Content

Up to this point, we have explained the basic usage of data volumes and data volume containers.
They can be utilized for data persistence, allowing you to access data again even after a container is destroyed.
However, currently, the data only exists in the data volume, and if the data volume itself is deleted, the data will be lost.
Therefore, it's a natural progression to think about taking backups, and Docker actually has functionality for that.
So, let's look at how to back up and restore data held in a data volume.
The backup sequence is as follows:

  1. Create a container that connects to both the data volume container and a directory on the host OS.
  2. In that container, create a tar file of the contents under the directory that interacts with the data volume container.
  3. Place the created tar file in the directory that serves as the mount point with the host OS.

Restoration is completed by reverting the file created during backup.
The commands based on the above are as follows:
Backup

docker run --volumes-from data-container -v /root/:/backup ubuntu tar cvf /backup/container-bkup.tar -C / tmp

Restore

docker run --volumes-from data-container -v /root/:/backup -it  ubuntu tar xvf /backup/container-bkup.tar -C /

The parts related to Docker use what has been explained so far.
The part after "ubuntu" specifies the command to be executed when the container starts.
In this case, it executes commands to create or restore a tar file.
Since the internal details of these commands are outside the scope of Docker, I will omit them here.
Please check them on your own.
With that, we have touched upon the basics of basics for Docker.
It's fun to start seeing words and commands that used to look like magic spells as something meaningful.
However, typing these commands one by one is tedious.
So, next, I will explain Dockerfiles, which allow you to execute the commands we've been running so far all at once.
Finally, we've reached something that is used quite regularly in actual development.

Leveraging Dockerfiles

Until now, we have downloaded Docker images, started containers, and sometimes mounted data volumes. However, all of these operations were executed via commands. While this might not be an issue for small-scale containers, as the scale of your containers grows, entering commands becomes tedious and prone to errors.

To address this, Docker has a file that allows you to batch process command operations. That file is the Dockerfile.

A Dockerfile can perform the following tasks:

  • Retrieve Docker images
  • Generate containers
  • Install applications
  • Generate new images

Using a Dockerfile makes it easier to create complex images and prepare similar environments on other host OSs. Since it is highly practical and likely to be used in actual development, let's try using it.

Points to Note When Creating a Dockerfile

Before creating a Dockerfile, keep the following three points in mind:

1. The filename must be "Dockerfile"
Docker has a feature called build. When you run a build, it reads the "Dockerfile" present in the directory where the build is executed and creates a unique image based on its contents. Although it is possible to use a different name with an option, it is generally recommended to name it "Dockerfile".

2. Do not place unnecessary files in the directory containing the Dockerfile
When building from a Dockerfile, Docker sends all files in that directory (and its subdirectories) to the Docker Daemon for processing. Therefore, if there are unnecessary files, they will all be sent, making the process unnecessarily heavy. Because of this, instead of creating a Dockerfile in an existing project, it is better to create a new directory, place the Dockerfile there, and build what you need.
If you absolutely must keep the Dockerfile in a directory with other files (e.g., in an existing project), you can create a .dockerignore file and list the paths of directories and files to be ignored during the build.

3. Keep commands to as few instructions as possible
When a Dockerfile retrieves an image, generates a container based on it, and performs tasks like installing applications, one "layer" is created for each instruction. Since there is a limit to the number of layers, you should reduce the number of instructions to avoid hitting this limit. This blog verified that the limit in the author's environment was 125. That's unexpectedly small, so it's important to consolidate instructions as much as possible.

Having covered the points to note, let's actually create one.

Side Note: What are Layers?

I mentioned that there is a limit to the number of layers, but let's confirm what a layer actually is. To get straight to the point: a layer is a "difference file" (diff).

Let's look at this in more detail. First, create the following Dockerfile and generate a Docker image.

FROM ubuntu

We will cover the syntax of Dockerfiles in a later section, so for now, just get a feel for it. Once the image is created, run docker save testimage | sudo tar -xC ../dumpimage to save the Docker image as a tar file and write it to the dumpimage directory. After writing, check the file structure with tree ../dumpimage; it will look like this:

../dumpimage
├── 29c4a2abb1c31c1d2f9a94ba2dd21b5678659799fecdf6df8c207d2d8854f9b4
│   ├── VERSION
│   ├── json
│   └── layer.tar
├── c6b84b685f35f1a5d63661f5d4aa662ad9b7ee4f4b8c394c022f25023c907b65.json
├── manifest.json
└── repositories

These file groups have the following characteristics:

  • layer.tar: Data of the root file system used by the container.
  • c6b...(omitted)..b65.json: Information for reproducing the execution environment, such as execution commands and environment variables.
  • manifest.json, repositories: Information regarding the image configuration.
  • VERSION, json: File groups for maintaining compatibility with past specifications.

layer.tar is the difference file—the layer—that is the subject here. In this case, since we pulled the ubuntu image from scratch, the differences related to that are included in layer.tar.

Next, let's see how these difference files increase. Delete the tar file in dumpimage, change the previously created Dockerfile as follows, and create the image again.

FROM ubuntu
RUN echo "Hello World" > /tmp/hello

This change creates /tmp/hello and writes the string "Hello World" into it. Once the Docker image is created, write the image's tar file to the dumpimage directory again. The file structure will look like this:

../dumpimage
├── 1c824fc1e048bc5bd521060d4c3509a368a94273fa544c9687a662eb8e683cee
│   ├── VERSION
│   ├── json
│   └── layer.tar
├── e76ae430a50a74b56a12319d7ff27d371796b7602650214f2341bffeb295e60c
│   ├── VERSION
│   ├── json
│   └── layer.tar
├── f9d9f3163e46ebeeccf044beacbc465481621a1a1856ce966766626b9919b89b.json
├── manifest.json
└── repositories

Previously, there was only one directory containing layer.tar, but now there are two. If you check the contents with tar --list -f ../dumpimage/e76ae430a50a74b56a12319d7ff27d371796b7602650214f2341bffeb295e60c/layer.tar | head, you will see the difference of creating and writing to tmp/hello.

2023-09-10_20h23_12.png

In this way, whenever the directory structure or file contents are changed, a difference file (a layer) is added. However, even if there are multiple changes in a single process, only one difference file is created, and it contains all those changes. To confirm this, change the Dockerfile as follows:

FROM ubuntu
RUN echo "Hello World" > /tmp/hello && echo "Hello World2" > /tmp/hello2

After regenerating the image and checking the difference files, it looks like this:

../dumpimage
├── 0002dfa61bedba5e5c99a05cb97a45f8791b299b9035a38553a3e0e92cdc2f0b.json
├── 1c824fc1e048bc5bd521060d4c3509a368a94273fa544c9687a662eb8e683cee
│   ├── VERSION
│   ├── json
│   └── layer.tar
├── dce77e3bdc12f9f180c2f7c48729989393b73561076b753c3b61f278a1d90f07
│   ├── VERSION
│   ├── json
│   └── layer.tar
├── manifest.json
└── repositories

Despite adding an extra write process, no additional difference file was created. This is because even if there are multiple processes, if the command itself is a single line, they are all aggregated into one layer.tar.

From this, we understand that a layer is a difference file created during image generation, and one difference file is created per line of processing. This should help you visualize why we recommended keeping instructions to a single line in the "Points to Note" section. Writing processes over many lines creates many difference files, which could eventually exceed Docker's management capacity. Therefore, by keeping instructions to a single line, we reduce the number of difference files and avoid hitting limits. While the reason is clear, I'm not confident I'd realize this was the issue if I encountered the error in a real environment!

Creating and Running a Dockerfile

Now, let's implement the installation of ping into an ubuntu image using a Dockerfile.
Create a Dockerfile in an arbitrary directory and write the following code.

FROM ubuntu
RUN apt-get update && apt-get install -y iputils-ping

FROM specifies the base Docker image when creating an image with a Dockerfile.
RUN specifies the commands to be executed during image creation.
The contents specified in RUN are stacked as layers.
In this case, we are basing it on the ubuntu image and installing iputils-ping.
As a side note, since a general Dockerfile like this is processed as a script, you should add the -y option when installing iputils-ping to install it without confirmation.
And, in the RUN section, we use && to combine commands.
As mentioned earlier, there are limits to Docker layers, so parts that can be combined should be joined using && or similar methods.

Once this is done, run docker build -t ping-image . to create the image.
The -t option allows you to specify the image name or tags to be assigned to the image name.
This time, we are not specifying a tag but assigning the tag name ping-image.
Also, note the period at the end.
This specifies the path to the Dockerfile to be built.
Since it's in the current directory, we specify it as ..
Executing the above command will process the instructions according to the Dockerfile, as shown in the image.

Untitled

Once the build is complete, verify that the Docker image exists in the terminal, and create a container with docker run -it ping-image.
If you can enter the container and confirm that ping works with ping localhost, then creating a container using a Dockerfile is successful.

Dockerfile Syntax

We've briefly touched on Dockerfiles and grasped the general flow.
Therefore, here we will look at the commands available within a Dockerfile to examine its contents in detail.

Dockerfile Format

A Dockerfile basically follows this format:

# Comment
INSTRUCTION argument

Instructions are not case-sensitive, but by convention, they are written in uppercase and arguments in lowercase.
If an instruction line becomes too long, you can use a \ (backslash) to break the line without starting a new instruction.

Shell Form and Exec Form

The shell form takes the following format, as seen in "Creating and Running a Dockerfile" or "Dockerfile Format":

INSTRUCTION argument

Note that this format executes commands through a shell (/bin/sh), so environment variables like $HOME can be used.
On the other hand, the exec form takes this format:

INSTRUCTION ["executable","parameter1","parameter2"]

If the RUN instruction from "Creating and Running a Dockerfile" were written in exec form, it would look like this:

RUN ["/bin/sh","-c","apt-get update && apt-get install -y iputils-ping"]

List of Dockerfile Instructions

Here, we will check some of the instructions available within a Dockerfile. For a complete list, please refer to the documentation as needed.

Instruction 1: FROM
Specifies the base image when creating an image with a Dockerfile. This is written at the very beginning of the Dockerfile.

Instruction 2: RUN
Executes commands on the OS within the container. There are two ways to write this: shell form and exec form.

Instruction 3: CMD
Describes the command that the container executes by default when it is run. Note that CMD can only be written once in a Dockerfile. If you write two CMD instructions, only the last one will be reflected during image creation.

By the way, RUN and CMD are similar because they both involve entering commands. However, please note that the timing of execution is different for RUN and CMD. RUN is reflected when generating the image, whereas CMD is reflected when the container is executed.

To see the difference in timing, let's modify the Dockerfile with ping that we created earlier. Change the RUN instruction in the Dockerfile to include the ping command as follows:

RUN apt-get update && apt-get install -y iputils-ping && ping localhost

Then, try to create an image with docker build -t ping-image2 ., but ping [localhost](http://localhost) will keep running, and the build will not complete. Even if you interrupt the process, since Docker considers the build incomplete, the image is not created. In this way, because RUN is a command executed during image creation, it is not appropriate to list things that need to keep running.

Next, let's try CMD. Delete the ping localhost that you previously wrote in RUN. Then, add an instruction like CMD ping [localhost](http://localhost). After that, building with docker build -t ping-image2 . will complete the build and create the image, unlike when it was added to RUN.

When you start a container from the above image with docker run -it ping-image2, you should be able to confirm that the ping localhost specified in CMD is executed.

From the above, we have confirmed that the execution timings of RUN and CMD are different. Since RUN is executed during image creation, it's better to describe commands that complete their processing, such as package installation or file copying. On the other hand, since CMD is executed when the container is started, it's appropriate to specify commands that you want to keep running, such as starting a web server.

Instruction 4: LABEL

This does not directly affect the operation of the Docker image, but it allows you to add metadata and information about the container.

Instruction 5: EXPOSE

This assigns and opens a port number when the container is executed. By setting this, you can enable connections from the host OS or other containers.

Instruction 6: ENV

ENV is an instruction for setting environment variables. You can set them by providing a key and a value. You can check the values set for environment variables using docker inspect.

Instructions 7 & 8: COPY, ADD

COPY and ADD are used during the image build process to copy files from the host OS into a directory within the container. While both copy host OS files into the container, they differ in the following ways:

  • COPY simply copies the files as-is.
  • ADD can extract compressed files such as tar or zip from the host OS while copying them into the container.

The syntax for COPY and ADD is as follows:

COPY source_path destination_path
ADD source_path destination_path

The destination path can be specified as either an absolute path or a relative path. However, note that a relative path is relative to the directory specified by the WORKDIR instruction, which will be described later.

Also, regarding the source path, the root directory is the directory where the Dockerfile build was executed. Therefore, please be aware that you cannot reference hierarchies above that directory.

The behavior of the copy depends on the path specification; if the destination is a directory, the source file is placed inside it. If the source is a directory, all files from the source directory are placed into the destination.

Instruction 9: ENTRYPOINT

ENTRYPOINT, like the CMD instruction, is executed when a container is generated. It is mostly the same as CMD, but the difference is that even if a command is specified during docker run, it will not be overwritten and will be executed reliably. Furthermore, when using the Exec form, ENTRYPOINT can be used in combination with CMD.

For example, consider the following ENTRYPOINT instruction:

ENTRYPOINT ["/bin/bash","-c"]

By doing this, executing docker run -it image is effectively executing docker run -it image /bin/bash -c. Therefore, when actually running the container, you only need to run docker run -it image pwd to execute docker run -it image /bin/bash -c pwd.

In this state, an error would occur if no argument is specified during docker run, so this is where you use the CMD instruction:

ENTRYPOINT ["/bin/bash","-c"]
CMD ["echo no-value"]

By using CMD like this to set a default argument, you can start the Docker container even without specifying an argument.

Instruction 10: VOLUME

VOLUME sets the specified directory as a mount point, allowing it to be mounted from the host OS or other containers. Since the explanation of volumes was provided earlier, it will be omitted here.

Instruction 11: WORKDIR

This instruction specifies the base directory for instructions such as RUN, CMD, ENTRYPOINT, COPY, and ADD in the Dockerfile. This instruction can be used multiple times; the directory specified by the WORKDIR instruction becomes the working directory for subsequent instructions, allowing you to switch working directories within a single Dockerfile.

Instruction 12: ONBUILD

ONBUILD specifies a command to be executed during a build. However, it is not executed when the Dockerfile containing the ONBUILD instruction is built. Instead, the specified command is executed when building a new Dockerfile that uses the image containing the ONBUILD instruction as its base.

Let's look at this in more detail. First, prepare two Dockerfiles. In the first Dockerfile, write the following:

FROM ubuntu
RUN apt-get update && apt-get install -y iputils-ping
ONBUILD RUN echo "This is a onbuild command"

Build this with docker build -t onbuild-image .. Nothing special happens, but the build completes. Next, write the following code in a second Dockerfile:

FROM onbuild-image
CMD echo "Hello World!"

This Dockerfile is built using the image we just created. Now, execute this Dockerfile with docker build -t onbuild-image ..

2023-09-09_09h30_19.png

Looking inside the red frame in the image, you can confirm that the command specified in the first Dockerfile has been executed. In this way, when you create an image again using an image that has an ONBUILD trigger, the command specified in ONBUILD is executed.

Now that we understand the meaning of ONBUILD, let's finally describe its benefits. ONBUILD is useful when separating the infrastructure image and the application image.

Basically, infrastructure configurations rarely change significantly. However, there are occasionally minor adjustments, such as slightly changing settings like conf files for the application's convenience. If you include the command to reflect conf settings in the infrastructure Dockerfile, you would need to rebuild it every time a change occurs. However, rebuilding for such changes would consume resources unnecessarily as it would be treated as a different image.

Therefore, by using ONBUILD, the command execution itself is performed on the application image side. This allows for suppressing unnecessary resource consumption.

Handling Dockerfile Cache

In Dockerfiles, there is a mechanism to use existing similar images if they already exist in order to shorten the build time.
Let's look at this specifically.
First, create the following Dockerfile.

# Dockerfile 1
FROM ubuntu
RUN apt-get update && apt-get install -y iputils-ping
CMD /bin/bash

Next, create another Dockerfile as follows.

# Dockerfile 2
FROM ubuntu
RUN apt-get update && apt-get install -y iputils-ping
CMD ping localhost

Then, build the first Dockerfile to create an image.
Next, build the second Dockerfile.
You will see that the common parts use the ones generated by the first one, as shown below.
2023-09-09_09h54_08.png
This is a feature of Docker where if an identical image has already been created, the previous image is reused as a cache instead of creating a new one.
Since the behavior is the same if the configuration is identical, this feature exists to improve resource efficiency.
In this way, Docker uses a cache during builds to speed up processing and suppress resource consumption.

However, the caching feature can also be a drawback.
This happens when the repository or the application to be installed is updated.
You would rebuild the Dockerfile to reflect that version at the time of the update.
However, if the same command is used, Docker uses the cached image, so the update will not be reflected even if you rebuild.
The following two points are examples of how to address this issue.

Solution ①: Do not use cache
The first workaround is to build without using the cache at all.
Specifically, by adding the --no-cache=true option like docker build -t image_name . --no-cache=true, it will not use the cache.
However, this method builds everything from scratch and consumes many resources, so it is not recommended for all cases.

Solution ②: Change the Dockerfile description
The second is to use the LABEL instruction to separate the instructions that use the cache from those that do not during the build.
A Dockerfile is read from the beginning, and the same image in the cache is used up to the point where the instructions are the same.
Therefore, by using LABEL or something similar to replace an instruction that does not affect the process, you can ensure that the cache is not used from that point onward.
Let's look at this more specifically.
First, rebuild Dockerfile 1 again.
Since the image has already been created, it uses the cache for everything.
Next, change Dockerfile 1 as follows.

FROM ubuntu
RUN apt-get update && apt-get install -y iputils-ping
LABEL cacheTest="test"
CMD /bin/bash

Try building this again.
2023-09-09_10h13_58.png
Then, you will see that what was using the cache until now has regenerated a new image.
In this way, by separating parts in the Dockerfile that use the cache from those that do not, you can place things that take time to download and have a low update frequency at the beginning to utilize the cache.
On the other hand, for things that require updates, you can place them after the LABEL instruction and regenerate the image by rewriting the LABEL when an update is needed.

Up to this point, we have looked at the overview of Dockerfiles.
Next, we will use these Dockerfiles to build a slightly more complex application.

Creating Slightly More Complex Containers with Docker

In this chapter, we will leverage what we have learned so far to create various containers.

Container ① Apache Container with Log Storage Settings

Here, we will create an Apache container configured to save logs to a volume.
The procedure is as follows:

  1. Create an httpd container to extract the httpd.conf used for Apache configuration. At this time, provide a directory mounted on the Host OS.
  2. Extract the httpd.conf from inside the container to the Host OS.
  3. Edit the obtained httpd.conf and change the log output destination to a directory in the data volume container.
  4. Create a Dockerfile to build the Apache container and run the build.
  5. Create a data volume container.
  6. Create a container from the Docker image created in step 4.

Let's begin.
First, create a directory on the Host OS side in an arbitrary location to store the httpd.conf.
In this case, I created an httpd directory under /root.
Next, pull the Docker image using docker pull httpd.
Once the pull is complete, run docker run --rm -v /root/httpd/:/tmp/ -it httpd /bin/bash.
By the way, please note that for the above command, you must append /bin/bash at the end; otherwise, you won't be able to perform command operations inside the container.
Also, if you start a container with the --rm option, the container itself is deleted the moment it is stopped.
Since this container is only used to copy httpd.conf to the Host OS, we start it with the --rm option.

Once inside the container, run cp /usr/local/apache2/conf/httpd.conf /tmp/ to copy httpd.conf to the mount point specified during container startup.
After performing the above, stop the container with exit and verify that the httpd.conf file exists in /root/httpd on the Host OS.
Once you have retrieved httpd.conf, open it in an editor of your choice.
Find the following line in httpd.conf:

CustomLog "logs/access_log" combined

And uncomment it.
After saving, create a Dockerfile and write the following:

FROM httpd
COPY ./index.html /usr/local/apache2/htdocs/
COPY ./httpd.conf /usr/local/apache2/conf/httpd.conf
EXPOSE 80

The COPY instruction is copying an index.html file to the DocumentRoot directory, but since we don't have an index.html yet, let's create one.
For this example, I created the following index.html in the same directory as the Dockerfile:

<h1>Hello Docker</h1>

Now, create the image with docker build -t apache-image ..
Once the image is created, run docker run -v apachelog-volume:/usr/local/apache2/logs --name=apachelog-container busybox to create a data volume container for the logs.
Although we created a data volume container here, a question comes to mind.
The Dockerfile had a VOLUME instruction earlier, so it seems like it would be fine to use a Dockerfile with that instruction to create a volume container, and indeed you can.
However, setting up a volume via a Dockerfile results in a random volume name, which causes the issue of not being able to assign an arbitrary name.
Since volume containers are rarely updated, there isn't much benefit to creating the volume in a Dockerfile, and given the disadvantage of random volume names, we are creating it via a command this time.
After creating the data volume container, run docker run --volumes-from apachelog-container -p 80:80 -d --name=apache-container apache-image to create a container named apache-container linked to the data volume container, connecting Host OS port 80 to container port 80.
Accessing http://localhost will confirm that "Hello Docker" is displayed.
Now that we've successfully created the container, let's finally check the logs.
Since we created a data volume container, we want to confirm that logs can be checked from a new container, so first, delete the container we just created.
Run docker run --volumes-from apachelog-container -it ubuntu. Once inside the container, if access_log exists in /usr/local/apache2/logs, you're done.

Container ②: Apache Container with nginx as a Reverse Proxy

In this section, we will create a reverse proxy environment combining nginx and Apache.
Please note that there is no description of concepts such as reverse proxies.
To create the above reverse proxy environment, you need to consider the following two points.

  1. Apache should not open its ports to the outside, ensuring that content is provided to external users only through nginx.
  2. Establish a mechanism for the two containers, nginx and Apache, to communicate.

Now, let's actually proceed.

First, to obtain the default.conf file required for the reverse proxy configuration from nginx, start the container with the command docker run --rm -v /root/rproxy:/tmp -it nginx /bin/bash.
Once inside the container, retrieve the default.conf file with cp /etc/nginx/conf.d/default.conf /tmp/.
Once you confirm it has been copied, open default.conf in an editor.
Look for the section where location / is described and add proxy_pass and its value as shown below.

location / {
    # Omitted
    # Add the following
    proxy_pass http://web-container/;
}

Then, create the following Dockerfile and build the image with docker build -t rproxy-image ..

FROM nginx
COPY ./nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80

Next, in order to create an Apache image, add an index.html with arbitrary content and the following Dockerfile in the same directory, then run docker build -t web-image ..

FROM httpd
COPY ./index.html /usr/local/apache2/htdocs/
EXPOSE 80

Now that the preparations for creating the containers are complete, we will create a network on Docker to allow the nginx and Apache containers to communicate.
Run docker network create web-network to create a space where the containers can exist on the same network.

Now that the preparations are ready, we will start the containers.
First, start the Apache container with docker run --name=web-container --net=web-network -d web-image.
In the command to start this Apache container, options are added or omitted for the following reasons:

① Assign a container name
The container name is written as --name=web-container so that it's immediately obvious it is the Apache container that nginx communicates with.
② Do not write the -p option
The -p option, which performs port linking, is specified only when linking with the host OS. In this case, since the connection target is another container, the -p option is not added.
③ Set the network
The --net option is set to link with the network created earlier.

Now that the Apache container has been created, let's create the nginx container.
Run docker run --name=rproxy-container --net=web-network -p 80:80 -d rproxy-image.
Since nginx communicates with the host OS, the -p option is set. Also, network linking is performed just as with Apache.

Once both containers are created, accessing http://localhost should confirm that the index.html created on the Apache side is displayed.
As a point of caution, please create the container on the Apache side first, then create the container on the nginx side.
This is because if you start from the nginx side, even if it can connect to the host OS side, an error will occur because the container to connect to on the container side does not yet exist.

With the above, we have constructed a reverse proxy using Docker.

Container ③: Database Container Using MySQL

Previously, we were configuring the server side.
So, this time, we will build a database, which is indispensable for application development, using Docker.
By being able to do this, you will get even closer to application development.
In this instance, we will also configure phpMyAdmin, which is essential when using MySQL.
Let's get started right away.
First, we will build MySQL.
Create an arbitrary directory and move into it.
We will work in /root/mydatabase.
After moving, create a data volume container with docker run -v db-volume:/var/lib/mysql/ --name=db-container busybox to enable data storage.
Next, create a network with docker network create mysql-nw to connect with phpMyAdmin.
With this, the preliminary preparations are complete, so we will create the MySQL container.
To create an image for MySQL, create an arbitrary directory (in this case, mysql) under /root/mydatabase and create the following Dockerfile.

FROM mysql:8
ENV MYSQL_ROOT_PASSWORD=dbpass01
CMD ["mysqld", "--character-set-server=utf8mb4", "--collation-server=utf8mb4_unicode_ci"]

docker build -t mysql-image . creates the image.
By the way, instead of extracting the database configuration file /etc/mysql/my.cnf to the host OS and configuring it, we are adding settings directly at container startup this time.
Also, we plan to connect to phpMyAdmin later, but we haven't set EXPOSE.
This is because when creating the official MySQL image, port number 3306 is automatically opened.
Once the image is created, start the container with docker run --volumes-from=db-container --net=mysql-nw --name=mysql-container -d mysql-image.
After confirming that the container is operating normally, move inside the container with docker exec -it mysql-container /bin/bash.
As a note, docker exec is used when executing commands against a container.
The docker run we've been using all along is against an image, so although the commands themselves are similar, please be careful as the targets are different.
Once inside the container, log in to the MySQL database with mysql -uroot -pdbpass01.
After logging in, run status; if the part in the red frame of the image is utf8mb4, the container has been generated successfully.
2023-09-09_15h45_59.png
Up to this point, MySQL settings are complete.
Therefore, database operations via CLI are possible.
However, in actual use, it's difficult to operate with CLI, so GUI is often used for database operations.
One frequently used tool for GUI operation with MySQL is phpMyAdmin, which we will build next.
I won't go into detail about specific features here, but various functionalities exist.
So, from here, we will enable interaction between the MySQL container created earlier and the phpMyAdmin container.
First, set up a directory for the phpMyAdmin container (in this case, phpmyadmin) under /root/mydatabase and create the following Dockerfile.

FROM phpmyadmin/phpmyadmin
ENV PMA_HOST=mysql-container \
    PMA_USER=root \
    PMA_PASSWORD=dbpass01

Note that the phpMyAdmin image is assigned port number 80 by default, and we will use that number, so EXPOSE is not described.
Create the image with docker build -t pma-image ..
After creating the image, start the container with docker run --net=mysql-nw --name=pma-container -p 8080:80 -d pma-image, linking it to the network the MySQL container belongs to while performing port mapping with the Host OS.
Once you've confirmed that the container is generated, accessing http://localhost:8080 will display the phpMyAdmin screen.
Now that the database construction is done, finally, confirm that the DB settings remain even if the container is destroyed.
First, stop the containers with docker stop mysql-container pma-container, then delete all stopped containers with docker container prune.
Then, start the MySQL and phpMyAdmin containers again in the following order: docker run -v db-volume:/var/lib/mysql/ --name=db-container busybox, docker run --volumes-from=db-container --net=mysql-nw --name=mysql-container -d mysql-image, and docker run --net=mysql-nw --name=pma-container -p 8080:80 -d pma-image.
After creating the containers, accessing http://localhost:8080 will show that the database created before destroying the containers remains.
With this, the database environment construction using Docker is complete.

Container ④: Redmine Container

We just created a database container.
With this, preparations for running applications are largely in place.
Therefore, here we will use Redmine to build an application connected to a database using containers.
Note that we will use the MySQL container and directories created earlier for the database container.
Let's begin.
First, create an arbitrary directory (in this case, redmine) under /root/mydatabase and create a Dockerfile with the following code.

FROM redmine
ENV MYSQL_ROOT_PASSWORD=dbpass01 \
    MYSQL_USER=root \
    MYSQL_PASSWORD=dbpass01

Create the image with docker build -t rm-image . and start the container with docker run --net=mysql-nw --name=rm-container -p 3000:3000 -d rm-image, linking it with the network the MySQL container belongs to and mapping it with the host OS port number 3000.
After confirming that the container is generated, accessing http://localhost:3000 will allow you to access the Redmine top page.
Untitled
With the above, building servers and environment construction for applications using containers is complete.

Managing Docker Containers Together — Let's Use Docker Compose

Up to this point, I think we have covered the basics of Docker.
However, at the same time, I feel it is tedious to create a Dockerfile for each container, build it, and then start the containers in order using docker run.
Personal projects might just be a hassle, but in a professional setting, it becomes extremely difficult if a server stops and you need to restart containers.
You would have to start each one individually while strictly following the correct order.
As the number of containers grows, management becomes very burdensome.
Docker Compose exists to solve these management issues caused by the increasing number of containers.
I will describe the specific syntax later, but by using Docker Compose, you can manage containers together with a few files and perform collective operations.
Therefore, even if the number of containers increases, the management burden will not become so large.
Now that the advantages of Docker Compose are visible, let's look at the specific way to write it.
Note that here, I will represent the content of "Creating Slightly More Complex Containers with Docker" using Docker Compose.
Therefore, while I will explain the syntax related to Docker Compose, I will not explain the content of the containers themselves.
Also, since many good articles appear if you search for the installation of Docker Compose, I will not describe it here.
Let's begin.

Side Note: Difference between Dockerfile and Docker Compose

I will briefly explain the difference between the Dockerfile we have created so far and Docker Compose.
As shown in the image below, Docker Compose is an extension of Docker that also possesses Dockerfile functionality.
Quoted from Docker Container Construction Procedure ② Docker Compose Edition
Quoted from Docker Container Construction Procedure ② Docker Compose Edition
Dockerfile is a file used to fetch an image from Docker Hub, apply custom settings, and create a single container image.
Therefore, a Dockerfile's role ends at image creation.
On the other hand, Docker Compose uses a definition file called "docker-compose.yml" and can perform the following for multiple containers:

  • build process to retrieve images (which Dockerfile performs)
  • Volume settings
  • Container generation while setting options
  • etc...

This is the main difference between Dockerfile and Docker Compose.
Docker Compose aggregates various functions performed in Docker, including Dockerfile features, into "docker-compose.yml".
Therefore, in professional environments, you should manage containers with Docker Compose.
In fact, if you search for "Docker environment construction" for any application, you will almost exclusively find content using Docker Compose.
It shows how standard it has become to use Docker Compose when handling containers.
While we started with docker commands and Dockerfiles to learn the basics, using Docker Compose for management is the standard for development.

Trying Out Docker Compose

Before expressing the containers created in "Creating Slightly More Complex Containers with Docker" using Docker Compose, let's try creating a simple ubuntu container with Docker Compose.
First, create a docker-compose.yml file in an arbitrary directory (this time, /root/docker-compose).
Once created, write the following code:

version: "3"
services:
  ub-test:
    image: ubuntu

Let's take a quick look at each part.
First, version is the version of the docker-compose.yml format.
Unless there's a specific reason, as of September 2023, version 3 is the latest, so we specify 3.
services is the block that defines the services.
Since everything belonging to the services block is basically a container definition, you can think of services as the code that indicates the start of container definitions.
By the way, docker-compose.yml represents hierarchy through indentation.
So, ub-test is a child of services, and image: ubuntu is a grandchild of services and a child of ub-test.
ub-test is the service name.
However, please note that the actual container name created will be "YAML_directory_name_service_name_serial_number".
image specifies the base image for the container.
In this case, we have set the ubuntu image.
Now that we are ready, run docker-compose up in the directory where docker-compose.yml is located.
If you can see a container named "docker-compose_ub-test_1" using docker ps -a or docker-compose ps, then you are done.

Next, let's try executing /bin/bash in ubuntu.
This means creating a container with the -it option and setting the command to /bin/bash.
In docker-compose.yml, the instructions corresponding to the -it option are tty: true and stdin_open: true.
Also, when specifying a command, use command.
You can think of this as the same as the CMD instruction in a Dockerfile.
Now, let's actually reflect this in docker-compose.yml.

version: "3"
services:
  ub-test:
    image: ubuntu
    tty: true
    stdin_open: true
    command: /bin/bash

Once written, start the container with docker-compose run ub-test and confirm that you have entered the container.
Regarding the difference from docker-compose up, docker-compose up starts all services defined in the file, whereas docker-compose run starts a specific service.
Since you cannot enter the container with docker-compose up, we are using docker-compose run this time.
Now that we've touched briefly on Docker Compose, next we will represent the containers from "Creating Slightly More Complex Containers with Docker" using Docker Compose.

Representing "Creating Slightly More Complex Containers with Docker" with Docker Compose

Container ①: Apache Container with Log Storage Settings in Docker Compose

Before making logs checkable from multiple containers, let's verify if we can run Apache.
Note that before running docker-compose.yml, you should have the configuration file httpd.conf and the index.html for screen display ready. Refer to "Container ①: Apache Container with Log Storage Settings" for details.

Create a docker-compose.yml and write the following code:

version: "3"
services:
  web-container:
    image: httpd
    # Equivalent to -p in docker run
    ports:
      - "80:80"
    # Equivalent to EXPOSE in a Dockerfile
    expose:
      - 80
    # Mounting local files to the container
    volumes:
      - ./index.html:/usr/local/apache2/htdocs/index.html
      - ./httpd.conf:/usr/local/apache2/conf/httpd.conf

Regarding volumes, docker-compose.yml does not have a command that directly replaces COPY in a Dockerfile. Therefore, in docker-compose.yml, an alternative method is taken to mount files individually to the container. In other words, what we want to do is the same as the following code in a Dockerfile:

COPY ./index.html /usr/local/apache2/htdocs/
COPY ./httpd.conf /usr/local/apache2/conf/httpd.conf

Once this is ready, generate the container with docker-compose up -d. Since this is a web server, we use the -d option to run it in the background.
Access http://localhost and confirm that the index.html you created earlier is displayed. Then, enter the container with docker-compose exec web-container /bin/bash and confirm that /usr/local/apache2/logs/access_log exists and you can check the logs.

Now that we've started Apache with Docker Compose, next we will set up a data volume container to allow checking logs from other containers as well.
First, use the convenient docker-compose down command to stop and delete the container. We stop/delete the container because editing docker-compose.yml while a container is running might change the container's state and prevent correct processing. Therefore, when modifying things around docker-compose.yml, it's best to stop the container first.

After stopping the container, add the following code under the services block of docker-compose.yml:

log-container:
  image: busybox
  volumes:
    - log-volume:/usr/local/apache2/logs/

This represents the docker run -v apachelog-volume:/usr/local/apache2/logs --name=apachelog-container busybox command we used earlier to create a data volume container in docker-compose.yml.
Next, create the following new block:

volumes:
  log-volume:

With docker commands, when creating a data volume container, the volume was created automatically if it didn't exist. However, docker-compose.yml will not create the volume for you simultaneously, so you must explicitly select a block to create the volume. Finally, add the following code to the web-container block:

volumes_from:
  - log-container

By adding this code to web-container, the container will be generated while setting the --volumes-from option to link it with the data volume container. The full code is as follows:

version: "3"
services:
  web-container:
    image: httpd
    ports:
      - 80:80
    expose:
      - 80
    volumes:
      - ./index.html:/usr/local/apache2/htdocs/index.html
      - ./httpd.conf:/usr/local/apache2/conf/httpd.conf
    volumes_from:
      - log-container
  log-container:
    image: busybox
    volumes:
      - log-volume:/usr/local/apache2/logs/
volumes:
  log-volume:

Now, start it again with docker-compose up -d and access http://localhost. Afterward, stop and delete the container with docker-compose down, start it again with docker-compose up -d, and enter the container with docker-compose exec web-container /bin/bash to look at the logs. You should be able to see the logs from the previous container's access.

Container ②: Apache Container with nginx as a Reverse Proxy in Docker Compose

Next, we will represent the container for "Container ②: Apache Container with nginx as a Reverse Proxy" using docker-compose.yml.
However, this time, instead of doing it exactly as in "Container ①: Apache Container with Log Storage Settings in Docker Compose", we will use both docker-compose.yml and Dockerfile.
By doing this, we can manage the internal container settings with Dockerfile and manage the container startup and connections with docker-compose.yml, splitting the management between files.
If internal settings are extensive, the docker-compose.yml code can become very long, so understanding this split method is beneficial.

Let's begin.
First, based on "Container ②: Apache Container with nginx as a Reverse Proxy", prepare the Dockerfile for the nginx side and the default.conf with the proxy_pass added, then store them in a specific directory.
On the Apache side, create a directory at the same level as the nginx settings directory and similarly prepare the Dockerfile and the index.html for screen display.
Then, create a docker-compose.yml one level above these directories.

The overall structure is as follows:

.
├── docker-compose.yml
├── httpd
│   ├── Dockerfile
│   └── index.html
└── rproxy
    ├── Dockerfile
    └── default.conf

Write the following code in docker-compose.yml:

version: "3"
services:
  rproxy-container:
    build: ./rproxy
    ports:
      - "80:80"
  web-container:
    build: ./httpd

The important part here is the build section.
This build block specifies the path where the Dockerfile is located.
By doing this, it reads and executes the Dockerfile, allowing us to delegate the image creation task to the Dockerfile.

With these steps complete, generate the container using docker-compose up -d. When you access http://localhost, the index.html located under the httpd directory will be displayed.

Container ③: Database Container Using MySQL & Redmine Container in Docker Compose

Finally, we will execute "Container ③: Database Container Using MySQL" and "Container ④: Redmine Container" using Docker Compose.
Since the process is largely the same, I will show the entire code first.

version: "3"
services:
  db-container:
    image: busybox
    volumes:
      - db-volume:/var/lib/mysql
  mysql-container:
    image: mysql:8
    environment:
      - MYSQL_ROOT_PASSWORD=dbpass01
      - MYSQL_DATABASE=redmine
    command: --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci
    depends_on:
      - db-container
    volumes_from:
      - db-container
    restart: always
  pma-container:
    image: phpmyadmin/phpmyadmin
    environment:
      - PMA_HOST=mysql-container
      - PMA_USER=root
      - PMA_PASSWORD=dbpass01
    ports:
      - 8080:80
    depends_on:
      - mysql-container
    restart: always
  redmine-container:
    image: redmine
    environment:
      - MYSQL_ROOT_PASSWORD=dbpass01
      - MYSQL_USER=root
      - MYSQL_PASSWORD=dbpass01
    ports:
      - 3000:3000
    depends_on:
      - mysql-container
    restart: always
volumes:
  db-volume:

Key points to notice are the depends_on block and the restart block.
I have introduced the environment block, but since its name suggests it sets environment variables, I will omit a detailed explanation.
First, regarding the depends_on block:
docker-compose.yml starts multiple containers, but by default, the startup order is not fixed and is essentially random.
However, in this configuration, an error will occur if the Data Volume Container doesn't exist before the MySQL container starts, preventing the container from launching.
Therefore, we need to specify the startup order.
This is where the depends_on block comes in.
By specifying a container name in this block, you can add a process that executes container startup after the specified container has started.
In this case, mysql-container has depends_on: db-container specified, so startup begins after the Data Volume Container has started, making errors less likely to occur.

However, the depends_on block only shifts the timing of startup; it does not wait for the specified container's creation to be complete before starting the next container.
Therefore, there is still a non-zero chance that the mysql-container starts before the Data Volume Container is fully ready, causing an error.
One way to handle this situation is to restart the mysql-container.
That is where the restart block is useful.
The restart block is an option to restart a container if it stops due to an error.
Here, I have specified always for the restart block, ensuring it restarts whenever an error occurs.
Thanks to this setting, at least errors caused by the Data Volume Container not being fully ready will be resolved by the restart.
That concludes the supplementary explanation.

Now, if you start the containers with docker-compose up -d, you can verify that you can access phpMyAdmin at http://localhost:8080 and Redmine at http://localhost:3000.
For reference, here is the version of docker-compose.yml that uses Dockerfiles.
The content of each Dockerfile is the same as those described in "Container ③: Database Container Using MySQL" and "Container ④: Redmine Container".

version: "3"
services:
  db-container:
    image: busybox
    volumes:
      - db-volume:/var/lib/mysql
  mysql-container:
    build: ./mysql
    depends_on:
      - db-container
    volumes_from:
      - db-container
    restart: always
  pma-container:
    build: ./phpmyadmin
    ports:
      - 8080:80
    depends_on:
      - mysql-container
    restart: always
  redmine-container:
    build: ./redmine
    ports:
      - 3000:3000
    depends_on:
      - mysql-container
    restart: always
volumes:
  db-volume:

Conclusion

In this article, we explored various aspects of Docker.
While researching, I discovered many features within Docker that made me realize I am still very much a beginner.
However, I can now understand what Dockerfile and docker-compose.yml are doing better than before, which is a step forward.
Since containers are a very convenient technology, I will continue to learn how to use them and hopefully explore Kubernetes as well.
It turned out to be quite a long post, but thank you very much for reading to the end.

Discussion