Introduction
With a solid understanding of Docker images, the next logical step is to learn how to launch and interact with containers effectively. This lesson focuses on the docker run command and its various options, particularly how to map network ports and manage container lifecycle. You'll learn how to make your containerized applications accessible from your host machine and manage them efficiently.
Key Concepts
The docker run Command
The docker run command is central to Docker operations. It creates a new container from a specified image and runs a command within that container. It has many options to configure the container's behavior, networking, storage, and more.
-
--name: Assigns a human-readable name to your container (e.g.,my-web-app). -
-d(Detached Mode): Runs the container in the background, freeing up your terminal. -
-it(Interactive/TTY): Allocates a pseudo-TTY and keeps STDIN open, allowing you to interact with the container (e.g., for shell access). -
--rm: Automatically removes the container when it exits.
Port Mapping (Publishing Ports)
Containers run in isolated network environments. To make services inside a container accessible from the host machine or from other networks, you need to map ports. This is done using the -p or --publish option.
-p host_port:container_port: Maps a specific port on the host machine to a specific port inside the container.- Example:
-p 8080:80maps host port 8080 to container port
- Example:
-
-P(Publish All): Randomly maps any exposed ports from the container to ephemeral ports on the host. Exposed ports are typically defined in the image's Dockerfile.
Example/Code
Running an Nginx Web Server Container
Let's run an Nginx web server container, naming it my-nginx and mapping port 8080 on our host to Nginx's default HTTP port 80 inside the container. We'll run it in detached mode.
bashdocker run --name my-nginx -p 8080:80 -d nginx
After running this, you can open your web browser and navigate to http://localhost:8080 to see the Nginx welcome page.
Interacting with a Running Container
To execute a command inside a running container, use docker exec:
bashdocker exec -it my-nginx bash
This command gives you a bash shell inside the my-nginx container. You can explore its file system and exit by typing exit.
Stopping and Removing Containers
bashdocker stop my-nginx docker rm my-nginx
Summary/Key Takeaways
-
docker runis used to create and start containers with various configurations. -
-d,--name, and-itare commondocker runoptions. -
Port mapping (
-p host_port:container_port) is essential for external access to containerized services. -
docker execallows running commands inside a running container. -
docker stopanddocker rmare used for managing the container lifecycle.