How to use docker container run command to manage containers

DockerDockerBeginner
Practice Now

Introduction

In this lab, you will gain practical experience using the docker container run command to effectively manage containers. You will learn how to run containers in detached mode for background execution and assign custom names for easier identification.

Furthermore, you will explore how to attach to running containers while keeping STDIN open, publish container ports to the host for external access, mount volumes to ensure data persistence, and configure containers by setting environment variables and adding host entries. These fundamental skills are essential for building and managing Dockerized applications.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL docker(("Docker")) -.-> docker/ContainerOperationsGroup(["Container Operations"]) docker(("Docker")) -.-> docker/ImageOperationsGroup(["Image Operations"]) docker(("Docker")) -.-> docker/VolumeOperationsGroup(["Volume Operations"]) docker/ContainerOperationsGroup -.-> docker/run("Run a Container") docker/ContainerOperationsGroup -.-> docker/ps("List Running Containers") docker/ContainerOperationsGroup -.-> docker/stop("Stop Container") docker/ContainerOperationsGroup -.-> docker/rm("Remove Container") docker/ContainerOperationsGroup -.-> docker/attach("Attach to Container") docker/ContainerOperationsGroup -.-> docker/exec("Execute Command in Container") docker/ImageOperationsGroup -.-> docker/pull("Pull Image from Repository") docker/VolumeOperationsGroup -.-> docker/volume("Manage Volumes") subgraph Lab Skills docker/run -.-> lab-555121{{"How to use docker container run command to manage containers"}} docker/ps -.-> lab-555121{{"How to use docker container run command to manage containers"}} docker/stop -.-> lab-555121{{"How to use docker container run command to manage containers"}} docker/rm -.-> lab-555121{{"How to use docker container run command to manage containers"}} docker/attach -.-> lab-555121{{"How to use docker container run command to manage containers"}} docker/exec -.-> lab-555121{{"How to use docker container run command to manage containers"}} docker/pull -.-> lab-555121{{"How to use docker container run command to manage containers"}} docker/volume -.-> lab-555121{{"How to use docker container run command to manage containers"}} end

Run a container in detached mode and assign a name

In this step, you will learn how to run a Docker container in detached mode and assign a custom name to it. Running a container in detached mode means that the container will run in the background, and you will not see its output directly in your terminal. Assigning a name makes it easier to identify and manage the container later.

First, let's pull the hello-world image. This is a very small image that is useful for testing if Docker is working correctly.

docker pull hello-world

You should see output indicating that the image is being pulled and then a message confirming it was pulled successfully.

Now, let's run the hello-world container in detached mode. We will use the -d flag for detached mode and the --name flag to assign a name. Let's name this container my-hello-world.

docker run -d --name my-hello-world hello-world

After running this command, Docker will print a long string of characters, which is the container ID. This indicates that the container has started in the background.

To verify that the container is running, you can use the docker ps command. This command lists all currently running containers.

docker ps

You should see a list of running containers, and one of them should be named my-hello-world. The STATUS column should show that the container exited a few seconds ago. The hello-world container is designed to run briefly, print a message, and then exit. Even though it has exited, it is still listed by docker ps because it was run in detached mode.

To see all containers, including those that have exited, you can use the docker ps -a command.

docker ps -a

This will show my-hello-world in the list, along with its status (Exited).

Attach to a running container and keep STDIN open

In this step, you will learn how to attach to a running container and keep the standard input (STDIN) open. This is useful for interacting with a container that is running a process that expects input, such as a shell.

In the previous step, we ran the hello-world container, which exited immediately. To demonstrate attaching, we need a container that stays running. A simple way to do this is to run an interactive shell in a container.

Let's pull the ubuntu image, which is a common base image for many applications.

docker pull ubuntu

Now, we will run an ubuntu container in detached mode (-d), allocate a pseudo-TTY (-t), and keep STDIN open (-i). We will also assign it a name, my-ubuntu. The command we will run inside the container is /bin/bash, which is the path to the Bash shell.

docker run -itd --name my-ubuntu ubuntu /bin/bash

The -i flag keeps STDIN open, allowing you to send input to the container. The -t flag allocates a pseudo-TTY, which is necessary for interactive shell sessions. The -d flag runs the container in detached mode.

You should see the container ID printed to your terminal, indicating that the container is running in the background.

Now, let's attach to the running my-ubuntu container using the docker attach command.

docker attach my-ubuntu

After running this command, you should see the prompt of the Bash shell inside the ubuntu container. You are now attached to the container's standard input, output, and error streams.

You can now interact with the container's shell. For example, you can run the ls command to list the files in the current directory inside the container.

ls

You should see the contents of the root directory (/) of the Ubuntu container.

To detach from the container without stopping it, you need to use a specific key sequence: CTRL+p followed by CTRL+q. Try pressing CTRL+p and then CTRL+q now.

You should be returned to your host machine's terminal prompt. The container is still running in the background. You can verify this using docker ps.

docker ps

You should see my-ubuntu listed as a running container.

If you were to simply press CTRL+c while attached, it would send a signal to the process running inside the container (the Bash shell), which would likely cause the container to stop. Using CTRL+p followed by CTRL+q is the standard way to detach without stopping the container.

Publish container ports to the host

In this step, you will learn how to publish ports from a Docker container to the host machine. This allows you to access services running inside the container from your host's network.

First, let's stop and remove the my-ubuntu container from the previous step to avoid conflicts.

docker stop my-ubuntu
docker rm my-ubuntu

You should see the name of the container printed after each command, confirming that it was stopped and removed.

Now, we will run a simple web server inside a container and publish its port to the host. We will use the nginx image, which is a popular web server.

Let's pull the nginx image.

docker pull nginx

Now, we will run an nginx container in detached mode (-d) and publish port 80 inside the container to port 8080 on the host machine. We will use the -p flag for port publishing, in the format host_port:container_port. We will also assign it a name, my-nginx.

docker run -d --name my-nginx -p 8080:80 nginx

The -p 8080:80 part maps port 80 inside the container (where Nginx listens by default) to port 8080 on your host machine.

You should see the container ID printed, indicating that the container is running in the background.

To verify that the port is published correctly and the web server is accessible, you can use the curl command on your host machine to access localhost on port 8080.

curl http://localhost:8080

You should see the default Nginx welcome HTML page in your terminal output. This confirms that you can access the Nginx web server running inside the container via port 8080 on your host.

You can also use docker ps to see the running container and its published ports.

docker ps

In the output, you should see my-nginx listed, and under the PORTS column, you should see 0.0.0.0:8080->80/tcp, indicating that port 80 inside the container is mapped to port 8080 on all host interfaces.

Mount a volume to persist data

In this step, you will learn how to use Docker volumes to persist data generated by and used by Docker containers. By default, the data inside a container is ephemeral; it is lost when the container is removed. Volumes provide a way to store data outside the container's filesystem, allowing it to persist even after the container is stopped or removed.

First, let's stop and remove the my-nginx container from the previous step.

docker stop my-nginx
docker rm my-nginx

Now, we will create a Docker volume. Volumes are managed by Docker and are stored in a dedicated area on the host machine.

docker volume create my-volume

You should see the name of the volume (my-volume) printed, confirming that it was created.

You can list existing volumes using the docker volume ls command.

docker volume ls

You should see my-volume in the list of volumes.

Now, we will run a new nginx container and mount the my-volume to the default Nginx webroot directory inside the container, which is /usr/share/nginx/html. This means that any files placed in /usr/share/nginx/html inside the container will actually be stored in the my-volume on the host.

We will run the container in detached mode (-d), publish port 80 inside the container to port 8081 on the host (-p 8081:80), assign it a name (my-nginx-volume), and use the -v flag to mount the volume. The format for mounting a named volume is volume_name:container_path.

docker run -d --name my-nginx-volume -p 8081:80 -v my-volume:/usr/share/nginx/html nginx

You should see the container ID printed, indicating that the container is running.

Now, let's place a simple HTML file in the mounted volume. We can do this by executing a command inside the running container using docker exec. We will create a file named index.html in /usr/share/nginx/html with some simple content.

docker exec my-nginx-volume sh -c 'echo "<h1>Hello from the volume!</h1>" > /usr/share/nginx/html/index.html'

This command executes a shell (sh -c) inside the my-nginx-volume container and runs the echo command to create the index.html file.

Now, let's access the web server on port 8081 on the host to see the content of the index.html file we just created.

curl http://localhost:8081

You should see <h1>Hello from the volume!</h1> in the output. This confirms that the file we created inside the container is being served by Nginx, and since it was written to the mounted volume, the data is persistent.

To demonstrate persistence, let's stop and remove the my-nginx-volume container.

docker stop my-nginx-volume
docker rm my-nginx-volume

Now, let's run a new container, mounting the same volume. We will name this new container my-nginx-volume-new and publish its port 80 to host port 8082.

docker run -d --name my-nginx-volume-new -p 8082:80 -v my-volume:/usr/share/nginx/html nginx

The new container is running, and it's using the same my-volume. Let's access the web server on port 8082.

curl http://localhost:8082

You should still see <h1>Hello from the volume!</h1> in the output. This is because the index.html file was stored in the my-volume, which persisted even after the original container was removed. The new container, by mounting the same volume, has access to the data that was previously written.

This demonstrates the power of volumes for persisting data independently of the container lifecycle.

Set environment variables and add host entries

In this step, you will learn how to set environment variables for a Docker container and how to add custom entries to a container's /etc/hosts file. Environment variables are a common way to configure applications running inside containers, and adding host entries can be useful for service discovery or overriding DNS resolution within the container.

First, let's stop and remove the my-nginx-volume-new container from the previous step.

docker stop my-nginx-volume-new
docker rm my-nginx-volume-new

Now, we will run a simple container and set an environment variable. We will use the ubuntu image again and run a command that prints the value of an environment variable. We will set an environment variable named MY_VARIABLE with the value hello_docker. We use the -e flag to set environment variables, in the format VARIABLE_NAME=value.

docker run --rm -e MY_VARIABLE=hello_docker ubuntu env | grep MY_VARIABLE

In this command:

  • --rm automatically removes the container when it exits.
  • -e MY_VARIABLE=hello_docker sets the environment variable MY_VARIABLE to hello_docker inside the container.
  • ubuntu is the image we are using.
  • env is the command executed inside the container to print all environment variables.
  • | grep MY_VARIABLE filters the output to show only the line containing MY_VARIABLE.

You should see MY_VARIABLE=hello_docker printed in your terminal output. This confirms that the environment variable was successfully set inside the container.

Next, let's learn how to add custom host entries to a container's /etc/hosts file. This can be useful if you need a container to resolve a specific hostname to a specific IP address without relying on external DNS. We use the --add-host flag for this, in the format hostname:ip_address.

We will run another ubuntu container and add a host entry that maps the hostname my-service to the IP address 192.168.1.100. We will then use the cat command to display the contents of the /etc/hosts file inside the container and use grep to check for our added entry.

docker run --rm --add-host my-service:192.168.1.100 ubuntu cat /etc/hosts | grep my-service

In this command:

  • --rm removes the container after it exits.
  • --add-host my-service:192.168.1.100 adds an entry to the container's /etc/hosts file mapping my-service to 192.168.1.100.
  • ubuntu is the image.
  • cat /etc/hosts is the command executed inside the container to print the hosts file.
  • | grep my-service filters the output to find the line with my-service.

You should see an output similar to 192.168.1.100 my-service in your terminal. This confirms that the custom host entry was added to the container's /etc/hosts file.

You can combine setting environment variables and adding host entries in a single docker run command if needed.

Summary

In this lab, you learned how to use the docker run command to manage containers. You started by running a container in detached mode using the -d flag and assigning it a custom name with the --name flag, verifying its status with docker ps and docker ps -a.

You then explored how to attach to a running container while keeping STDIN open, publish container ports to the host using the -p flag for network accessibility, mount a volume with the -v flag to ensure data persistence beyond the container's lifecycle, and configure the container's environment by setting environment variables with the -e flag and adding host entries using the --add-host flag.