“docker run” Command Examples

In Docker, the command “docker run” is used to create and run a new container based on a specified Docker image. Containers are lightweight, isolated environments that can run applications with their dependencies, making it easier to package and deploy software across different environments.

When you execute the “docker run” command, Docker performs several steps:

  • Image Pull: If the specified image is not already present on your local system, Docker will attempt to download it from a registry (such as Docker Hub) unless you have specified a local image.
  • Container Creation: Docker creates a new container based on the specified image. This container is an isolated instance that runs independently from other containers and the host system. It provides its own file system, network interfaces, and resource allocation.
  • Command Execution: You can provide a command or a script to execute within the newly created container. This command will be run as the main process inside the container. It could be a simple command, like running a shell script, or a complex command that starts a web server, database, or any other application.
  • Container Startup: Docker starts the container and executes the command you specified. It redirects the standard input, output, and error streams to your terminal by default, allowing you to interact with the container and see its output.
  • Container Termination: Once the command or process running inside the container completes, the container terminates. However, you can also configure Docker to keep the container running in the background, detached from your current terminal session.

docker run Command Examples

1. Run command in a new container from a tagged image:

# docker run image:tag command

2. Run command in a new container in background and display its ID:

# docker run --detach image command

3. Run command in a one-off container in interactive mode and pseudo-TTY:

# docker run --rm --interactive --tty image command

4. Run command in a new container with passed environment variables:

# docker run --env 'variable=value' --env variable image command

5. Run command in a new container with bind mounted volumes:

# docker run --volume /path/to/host_path:/path/to/container_path image command

6. Run command in a new container with published ports:

# docker run --publish host_port:container_port image command

7. Run command in a new container overwriting the entrypoint of the image:

# docker run --entrypoint command image

8. Run command in a new container connecting it to a network:

# docker run --network network image
Related Post