For extensive information see the docker reference. It has all of the information here and is more in-depth.
This is more of highlight / quick useful things you to remember.
Docker without sudo
You need to add your user to the docker
group:
$ sudo gpasswd -a $USER docker
You probably need to restart terminal or logout for this to take effect.
Docker run
Docker run is what lets you spin up containers from images.
$ docker run <image>
Useful flags:
-
--name <name>
: sets the container name -
--rm
: delete the container as soon as it stop -
--publish
or-p
: maps a containers ports to host ports$ docker run -p <host>:<container> <image>
if you want to restrict them to a certain subnet:
$ docker run -p <subnet>:<host>:<container> <image>
for example, to map port 8080 to 8080 and have it only accessible over localhost:
$ docker run -p 127.0.0.1:8080:8080 <image>
-
--interactive
or-i
: connect to the STDIN of the command inside the container -
--tty
or-t
: gives a tty (usually not useful without-i
option) -
--detach
or-d
: runs container in the background -
--network <network>
: connect the container to a network (useful for containers which need to communicate)
Networks
Networks let you connect containers to other containers or workloads.
Lets say for example you are running a MySQL database in a docker container and an app which connects to the database in a different container. Normally you would just connect over localhost
, but since your app is in a container, localhost
in your app’s container is not the same as inside the MySQL container.
You can create a network to connect your app to the database.
First create the network:
$ docker network create <network-name>
Once you have a network, you need to connect both your containers to it.
For existing containers:
$ docker network connect <network-name> <container-id>
Or when making a container using docker run:
$ docker run --network <network-name> <image>
Now that both the containers are on the same network, instead of using localhost
for your apps connection, you can use the name of the MySQL container. This will automatically resolve to the ip of the MySQL container.
Quick usage
Listing containers
You can running containers:
$ docker ps
Or the long way:
$ docker container ls
To see all containers add the -a
flag to either command.
Removing containers
You can remove a container using:
$ docker rm <container-id>
Listing images
You can show all images using:
$ docker image ls
Removing images
You can remove an image like so:
$ docker image rm <image-name>
Removing none images
When listing images there is usually a bunch called <none>
.
To properly remove them without breaking stuff run:
$ docker rmi $(docker images -f "dangling=true" -q)