πŸƒβ€β™‚οΈ Mastering the docker run Command

πŸ“‹ Basic Syntax

docker run [OPTIONS] IMAGE_NAME[:TAG] [COMMAND] [ARG...]

If the tag version is not specified, Docker defaults to latest.

βš™οΈ Common Options

OptionDescription
--nameAssigns a custom name to the container
-e or --envSets environment variables inside the container
-d or --detachRuns the container in detached mode (background)
-p or --publishMaps container port to host port (host_port:container_port)

πŸ› οΈ Practical Examples

Executing Commands in a Container

docker run ubuntu sleep 5
  • Starts the container β†’
  • Runs sleep for 5 seconds β†’
  • Stops the container

Verify the execution:

docker ps -a

πŸ“‚ Accessing Files in a Running Container

docker exec [containerID] cat /etc/hosts

Prints the content of the hosts file.

πŸ”— Attach, Detach, and Reattach

docker run -d ubuntu

Docker Detach Example

πŸ–₯️ Interactive Mode

docker run -it centos bash
  • -i: Interactive input
  • -t: Attach to the terminal
  • Opens the Bash shell inside the container

🌐 Port Mapping

docker run -p 80:5000 kodekloud/webapp
  • 80: Host port
  • 5000: Container port

πŸ“‚ Volume Mapping (Persistent Data)

docker run -v /opt/datadir:/var/lib/mysql mysql

Maps the external folder /opt/datadir to the MySQL container’s data directory.

πŸ”Ž Inspect Container Details

docker inspect [containerName]

Docker Inspect Example

πŸ“ Viewing Container Logs

docker logs [containerName]

Docker Logs Example

🌈 Setting Environment Variables

docker run -e APP_COLOR=blue simple-webapp

Verify the environment variable:

docker inspect [containerName]