In a previous lesson, we learned about docker images and now we know that:
Docker images are blueprints of docker containers
To bring these blueprints to life is to create a docker container using the docker run
command. For an instance let's consider we have an image with name ubuntu:latest
already built onto our system.
The command:
docker run [OPTIONS] IMAGE_NAME[:TAG|@DIGEST] [COMMAND] [ARGS...]
Examples:
docker run ubuntu:latest
docker run -it -p 5000:80 -e "MODE=DEBUG" my_mongo_image
Options used in docker run:
There are a plethora of options available for docker run
but here we will learn a few keys ones.
-p HOST_PORT:CONTAINER_PORT[/PROTOCOL]
The -p
option publishes the specified container port to the specified host machine port.
Example:
docker run -p 5000:80/tcp my_mongo_image
-i -t
By default the processes running inside a docker container can not read from the host machine standard input or STDIN. To over come this issue and provide input to the container processes from host machine use the -i
flag. The -t
flag is used to create a pseudo terminal for our app inside the container, now user can see every prompt from the app straight to the host machine terminal. Both options are used together as -it
.
Example:
docker run -it ubuntu:latest
-e VAR=VALUE
The -e
option sets environment variables in the container. If the variable in this option are already specified in Dockerfile then ones in dockerfile be overridden. Specifying a variable without any value will use the values from host machine.
Example:
docker run -e USER=ADMIN -e PASSWD=hd7632b alpine_image:jimjam
--name CONTAINER_NAME
Every container is assigned an internal IP address which does not coincide with the host IP space. So, if multiple containers want to communicate then they must contact via the assigned IP address but here we can not guarantee that a container will be assigned the same IP every time, there is an easy workaround this process and it is to contact a container via it's name. Docker assigns a random name to container, unless specified. Providing a name explicitly, creates an entry for the conatiner IP and the name inside docker's embedded DNS.
Example:
docker run --name logger_container alpine_image:jimjam
--network NETWORK_NAME
Communication between containers can be managed seemlessly using --network. Docker has 4 types of network to choose from these include host, bridge, none, and user-defined. Default is bridge.
Example:
docker run --network host alpine_image:jimjam
docker run --network custom_subnet1 alpine_image:jimjam
docker run --network none alpine_image:jimjam
-v VOLUME_NAME:CONTAINER_PATH
The -v
flag is used to mount a volume in the docker container. Value for -v
is the volume name and path inside container seperated by a :
Example:
docker run -v vol2:/code/app alpine_image:jimjam
Next, see how data is managed in docker, click here
Resources:
- (docs)docker run reference
- (video)What is a container in Docker