docker run
The docker run command is used to create and start a new container from a specified image. It is one of the most frequently used Docker commands. Here is an in-depth explanation of docker run along with examples and relevant switches and parameters.
Basic Syntax
Key Options and Parameters
-d, --detach: Run container in background and print container ID.
docker run -d nginx-p, --publish: Publish a container's port(s) to the host.
docker run -d -p 80:80 nginx--name: Assign a name to the container.
docker run --name mynginx -d nginx-e, --env: Set environment variables.
docker run -e MY_ENV_VAR=value -d nginx-v, --volume: Bind mount a volume.
docker run -v /host/path:/container/path -d nginx--rm: Automatically remove the container when it exits.
docker run --rm -d nginx-it: Run container in interactive mode with a terminal.
docker run -it ubuntu /bin/bash--network: Connect a container to a network.
docker run --network mynetwork -d nginx
Examples
Running a Simple Container
docker run hello-worldThis command runs the
hello-worldimage, which prints a message and exits.Running a Web Server
docker run -d -p 8080:80 nginxThis command runs an Nginx web server in the background and maps port 80 of the container to port 8080 on the host.
Running a Container with Environment Variables
docker run -d -e MYSQL_ROOT_PASSWORD=my-secret-pw mysqlThis command runs a MySQL container with the root password set via an environment variable.
Running a Container with a Volume
docker run -d -v /my/host/data:/var/lib/mysql mysqlThis command runs a MySQL container and mounts the host directory
/my/host/datato/var/lib/mysqlin the container.Running an Interactive Shell
docker run -it ubuntu /bin/bashThis command runs an Ubuntu container and opens an interactive bash shell.
Running a Container with a Custom Name
docker run --name mynginx -d nginxThis command runs an Nginx container with the name
mynginx.Running a Container on a Custom Network
docker network create mynetwork docker run --network mynetwork -d nginxThis command first creates a custom network named
mynetworkand then runs an Nginx container connected to this network.
Conclusion
The docker run command is versatile and powerful, allowing you to configure and run containers with various options and parameters. Understanding these options helps you effectively manage and deploy your Docker containers.