Running Docker Containers Interactively
Running Docker containers interactively allows you to access the container's shell and interact with it directly, making it useful for debugging, testing, and development purposes.
Starting a Container Interactively
To start a Docker container interactively, you can use the docker run
command with the -i
(interactive) and -t
(allocate a pseudo-TTY) flags. For example, to start an Ubuntu container interactively:
docker run -it ubuntu:latest /bin/bash
This command will start a new Ubuntu container and attach your terminal to the container's shell, allowing you to interact with it directly.
Executing Commands in a Running Container
Once you have a container running interactively, you can execute commands within the container using the docker exec
command. For example, to run the ls
command in the running container:
docker exec -it < container_id > ls
Replace <container_id>
with the ID or name of your running container.
Attaching to a Running Container
If you have a container that is already running, you can attach to it interactively using the docker attach
command:
docker attach <container_id>
This will attach your terminal to the container's shell, allowing you to interact with it directly.
Detaching from a Container
To detach from a running container without stopping it, use the keyboard shortcut Ctrl+P Ctrl+Q
. This will detach you from the container, but the container will continue running in the background.
Stopping a Container
To stop a running container, you can use the docker stop
command:
docker stop <container_id>
This will gracefully stop the container, allowing it to perform any necessary cleanup before exiting.