Running Docker Containers Interactively
After downloading and pulling Docker images, the next step is to run them as containers. Docker containers are instances of Docker images that can be started, stopped, and managed. Running containers interactively allows you to access the container's shell and interact with it directly.
Starting a Container Interactively
To start a Docker container interactively, you can use the docker run
command with the -it
(interactive terminal) option.
## Start an Ubuntu container interactively
docker run -it ubuntu:22.04 /bin/bash
This command will start a new Ubuntu 22.04 container and attach your terminal to the container's shell, allowing you to interact with it directly.
Exploring the Container
Once inside the container, you can explore its contents and run various commands. For example, you can check the system information, install additional packages, or run your application.
## Inside the Ubuntu container
root@container-id:/## cat /etc/os-release
root@container-id:/## apt-get update && apt-get install -y nginx
root@container-id:/## nginx -v
Exiting and Detaching from the Container
To exit the interactive container, you can use the exit
command, which will stop and remove the container.
If you want to detach from the container while keeping it running, you can use the keyboard shortcut Ctrl+P Ctrl+Q
.
## Detach from the running container
root@container-id:/## Ctrl+P Ctrl+Q
This will detach you from the container, leaving it running in the background.
Reattaching to a Running Container
You can reattach to a running container using the docker attach
command.
## Reattach to the running container
docker attach container-id
By understanding how to run Docker containers interactively, you can easily explore, test, and debug your containerized applications during the development and deployment process.