Managing Docker Containers
Once you have Dockerized your application, you'll need to learn how to manage the lifecycle of your Docker containers. This includes starting, stopping, and interacting with your containers.
Starting and Stopping Containers
You can start a new container using the docker run
command. This command creates a new container from a specified Docker image and starts it.
## Start a new container
docker run -d -p 8080:5000 my-flask-app
The -d
flag runs the container in detached mode, which means it runs in the background. The -p
flag maps the host's port 8080 to the container's port 5000.
To stop a running container, you can use the docker stop
command, passing the container ID or name as an argument.
## Stop a running container
docker stop my-flask-app
Listing and Inspecting Containers
You can list all running containers using the docker ps
command. To see all containers, including stopped ones, use the docker ps -a
command.
## List all running containers
docker ps
## List all containers (running and stopped)
docker ps -a
To get detailed information about a specific container, you can use the docker inspect
command.
## Inspect a container
docker inspect my-flask-app
This will output a JSON-formatted object containing various details about the container, such as its configuration, network settings, and resource utilization.
Attaching to and Logging Containers
You can attach to a running container's standard input, output, and error streams using the docker attach
command.
## Attach to a running container
docker attach my-flask-app
To view the logs of a container, you can use the docker logs
command.
## View the logs of a container
docker logs my-flask-app
This will display the standard output and standard error logs of the container.
Container Lifecycle Management
Docker provides a set of commands for managing the lifecycle of your containers, including:
docker start
: Start a stopped container
docker stop
: Stop a running container
docker restart
: Restart a container
docker rm
: Remove a container
By mastering these container management commands, you'll be able to effectively control and maintain your Dockerized applications.