A container is a running docker image. You can consider container as lightweight virtual machine, but

  • more agile than VM
  • easy integrate with your existing IT processes like monitoring, backup and etc
  • share common operating system and software libraries
# run container mymongo from mongo image
docker run --name mymongo -d -p 27017:27017 -v ~/data:/data/db mongo

# list of running containers
docker ps

# stopped containers
docker ps --filter "status=exited"

#stop all containers:
docker stop $(docker ps -a -q)

#stop all containers by force
docker kill $(docker ps -q)

#remove all containers
docker rm $(docker ps -a -q)

Run container

The run command syntax

docker run [OPTIONS] IMAGE [COMMAND] [ARG...]

Below, some most useful options

Option Description
--env, -e Sets simple (non-array) environment variables in the container you’re running, or overwrite variables that are defined in the Dockerfile of the image you’re running. You can also use variables that you’ve exported to your local environment.
docker run --env VAR1=value1 --env VAR2=value2 ubuntu env | grep VAR

# exported variables
export VAR1=value1
export VAR2=value2

docker run --env VAR1 --env VAR2 ubuntu env | grep VAR
it Allocates a pseudo-TTY connected to the container’s stdin; creating an interactive bash shell in the container.
-p Creates a port mapping rule like -p ip:hostPort:containerPort. containerPort is required. If no hostPort is specified, Docker will automatically allocate one.
docker run --name mymongo -d -p 27017:27017 -v ~/data:/data/db mongo
--restart Specifies a container’s restart policy. Possible values:
  • no do not automatically restart the container when it exits (default).
  • on-failure[:max-retries] restarts only if the container exits with a non-zero exit status. Optionally, limit the number of restart retries the Docker daemon attempts.
  • unless-stopped restarts the container unless it is explicitly stopped or Docker itself is stopped or restarted.
  • always - always restarts the container regardless of the exit status. When you specify always, the Docker daemon will try to restart the container indefinitely. The container will also always start on daemon startup, regardless of the current state of the container.
docker run --restart=always redis
-v Bind mount a volume.
docker run --name mymongo -d -p 27017:27017 -v ~/data:/data/db mongo
Here "~/data" is directory on host machine, "/data/db" directory in the docker container, and : is separator. If directories do not exist, they will be created. You can append ":ro" to the container directory to make it read-only.