Running and Managing Docker Containers
Once you have a basic understanding of Docker containers and how to name them, you can start running and managing your Docker containers. This section will cover the essential commands and techniques for working with Docker containers.
Running Docker Containers
The primary command for running a Docker container is docker run
. This command allows you to start a new container based on a specified Docker image.
## Run a Ubuntu container in detached mode
docker run -d ubuntu
## Run a container with a custom name
docker run -d --name my-ubuntu ubuntu
In the above examples, we're running a Ubuntu container in detached mode (-d
) and assigning a custom name to the container (--name
).
Managing Docker Containers
Once you have running containers, you can use various Docker commands to manage them.
Listing Containers
To list all running containers, use the docker ps
command:
docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
a1b2c3d4e5f6 ubuntu "/bin/bash" 10 seconds ago Up 9 seconds my-ubuntu
To list all containers, including those that are not running, use the docker ps -a
command:
docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
a1b2c3d4e5f6 ubuntu "/bin/bash" 10 seconds ago Up 9 seconds my-ubuntu
b7c8d9e0f1g2 ubuntu "/bin/bash" 1 minute ago Exited (0) 30 seconds ago silly_hopper
Stopping and Starting Containers
You can stop a running container using the docker stop
command:
docker stop my-ubuntu
To start a stopped container, use the docker start
command:
docker start my-ubuntu
Removing Containers
To remove a container, use the docker rm
command:
docker rm my-ubuntu
Note that this will remove the container, but not the Docker image it was based on.
Monitoring and Troubleshooting Containers
Docker provides various commands to monitor and troubleshoot your containers:
docker logs
: View the logs of a running container
docker inspect
: Inspect the details of a container
docker stats
: Display resource usage statistics for your containers
By using these commands, you can gain insights into the behavior and performance of your Docker containers, making it easier to manage and maintain your applications.