Running Docker Containers from Images
Starting a Docker Container
Once you have a Docker image, you can start a container based on that image using the docker run
command.
$ docker run -d --name my-nginx-container nginx:latest
This command will start a new Docker container using the nginx:latest
image, and assign the name my-nginx-container
to the container.
The -d
option runs the container in detached mode, which means the container will run in the background.
Exposing Container Ports
If your containerized application needs to be accessible from outside the container, you need to map the container's ports to the host system's ports using the -p
option.
$ docker run -d -p 8080:80 --name my-nginx-container nginx:latest
This command will map the container's port 80 to the host's port 8080, allowing you to access the Nginx web server running inside the container from the host system.
Attaching to a Running Container
You can attach to a running container and interact with it using the docker attach
command.
$ docker attach my-nginx-container
This will attach your terminal to the running container, allowing you to view the container's output and interact with it.
Executing Commands in a Container
You can also execute commands inside a running container using the docker exec
command.
$ docker exec -it my-nginx-container bash
This command will start a new bash session inside the my-nginx-container
container, allowing you to run commands and interact with the container's environment.
The -it
options ensure that the command is run in interactive mode with a terminal.
Stopping and Removing Containers
When you're done with a container, you can stop it using the docker stop
command, and remove it using the docker rm
command.
$ docker stop my-nginx-container
$ docker rm my-nginx-container
These commands will first stop the running container, and then remove it from the system.
By understanding how to run, manage, and interact with Docker containers, you can effectively deploy and manage your containerized applications.