Container

A Container ia basically an Image that is executed.

To execute a container you can use the following command:

docker container run [OPTIONS] <imagename> [COMMAND] [ARG]

where

[OPTIONS], is the flags used to execute the command

[COMMAND] is the instruction that you could execute the container if we don’t like the default command inside the image

[ARG] is the param that we can pass to the container

What does it happen when we launch a container?

First of all Docker tries to find the image locally. If it doesn’t find it it serach into Docker hub.

If we don’t specify a tag the “latest” will be used.

And finally we have our container!

Docker will assign a virtual IP in the private network of the container. After that the binding will be executed

Example

To see all important aspects let’s instantiate a nginx container sing 1.19.5-alpine image

P.S.: Alpine is a Linux distribuition

docker container run -it --rm -d -p 8080:80 --name web nginx:1.19.5-alpine

where:

-it, is a combination of -i and -t, where -i means interact with the standard input and -t interact with the container with a tty interface

-rm, the container will be automatically deleted once terminated

-d, once instantiated the execution will be in background mode

-p 8080:80, the container port 80 will be linked to the 8080 port of the host

–name web, give the “web’ name to the container

once executed you can reach the server at the address http://localhost:8080

Add a volume

In order to associate a local volume (folder) to a container folder we need to add a param in our command line which map our local folder to container folde:

-v /your/local/folder:/container/folder

So the new complete command line will be:

docker container run -it --rm -d -p 8080:80 --name web -v /your/local/folder:/container/folder nginx:1.19.5-alpine

In our specific example, we would point the container folder /usr/share/nginx/html, in which there is the html folder for nginx to our local, previously created, folder /Users/xxx/nginx/html, to override that specifi folder

docker container run -it --rm -d -p 8080:80 --name web -v /Users/xxx/nginx/html:/usr/share/nginx/html nginx:1.19.5-alpine