1.1 The docker run Command
One of the most important commands in Docker is docker run. It lets you start new containers based on existing images. Just a reminder, an image is like a template, while a container is its actual instance (exactly like classes and objects in OOP). In this lecture, we’ll dive into how to use the docker run command to create and start your first container, as well as explore more advanced use cases.
The docker run command is used to create and run containers from Docker images. It’s one of the most frequently used commands and comes with tons of options to configure container behavior.
The basic syntax of the docker run command:
docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
Where:
- OPTIONS: parameters for configuring the container (e.g., ports, volumes, environment variables).
- IMAGE: the name of the image to create the container from.
- COMMAND: the command to be executed inside the container.
- ARG...: arguments for the command.
A simple example of using docker run
Let's start with a simple example to understand how the docker run command works.
docker run hello-world
This command will pull the hello-world image from Docker Hub (if it’s not already downloaded) and run it. The container will execute the command embedded in the image and display the following message:
Hello from Docker!
This message shows that your installation appears to be working correctly.
...
1.2 Running with Parameters
1. Running a Container in Detached Mode
By default, containers are launched in interactive mode, and their output is shown in your terminal
. However, you can run the container in the background using the -d (detached mode)
option.
docker run -d nginx
This command will launch the Nginx web server in the background. Docker will return the container ID, which can be used for further container management.
2. Assigning a Name to the Container
To make container management easier, you can assign a name to the container using the --name
parameter.
docker run -d --name my_nginx nginx
Now your container will have the name my_nginx
, and you can refer to it by name in other Docker commands.
3. Viewing Container Output
You can start a container with a command that outputs results to your terminal. This is done with the -i (interactive)
and -t (pseudo-TTY)
options.
docker run -it ubuntu bash
This command will launch a container based on the ubuntu
image and open an interactive Bash terminal inside the container. You can execute commands in this terminal just like in a regular Ubuntu system.
GO TO FULL VERSION