Start containers
Start the Jenkins container by specifying the port (outside:inside) and the volume associated :
docker run -p 8080:8080 -v jenkins_home:/var/jenkins_home jenkins/jenkins:lts
Run a container by specifying the in:out port, the volume src:dest, the working directory on the container to run a command and the image name :
docker run -p 8080:3000 -v $(pwd):/var/www -w "/var/www" node npm start
On windows the current directory : $(pwd)
becomes %cd%
Beware on Windows, the src of the volume can only be in a /c/Users
folder.
Start a container by overriding the entry point of the image by a sh execution (or anything else):
docker run -ti --entrypoint /bin/sh myImage
Variant when we need to pass a entrypoint with several tokens (here tail -f /dev/null)
:
docker run -ti --entrypoint tail myImage -f /dev/null
Useful flags :
-n fooname
(alias for --name fooname
): assign a name to the container
--rm
: remove the container when exited
-u
: set the username or UID that runs the container (format: name|uid[:group|gid]
]
-p OUT:IN
: Publish a container’s port to a specific port of the host
-p IN
: Publish a container’s port to a random port of the host
-P
: Publish Publish all exposed ports to random ports
--restart RESTART_POLICY
: Restart policy to apply when a container exits (defaut no)
Expected values :
no
: Do not restart the container (default)
on-failure
: Restart the container if it exits due to an error, which manifests as a non-zero exit code.
always
: Always restart the container if it stops. If it is manually stopped, it is restarted only when Docker daemon restarts or the container itself is manually restarted. (See the second bullet listed in restart policy details)
unless-stopped
: Similar to always, except that when the container is stopped (manually or otherwise), it is not restarted even after Docker daemon restarts.
--add-host list
: add a custom host-to-IP mapping (host:ip).
It add the host:ip list into the container’s /etc/hosts file.
Example : --add-host gitlab.david.com:172.17.0.1
-e key=value
(alias for --env key==value
) : set simple (non-array) environment variables in the container to start, or overwrite variables that are defined in the Dockerfile of the image you’re running .
You can also use variables that exported from your local environment.
Example with the two ways :
export VAR1=value1
docker run --env VAR1 --env VAR2=value2
--env-file list
: set environment variables from file(s)
Ex: docker run --env-file env.list
where env.list is a plain file with key=value by line.
-l or --label
: add a label to the container
Example to add two labels : docker run ... -l co.elastic.logs/enabled=true -l myapp
Set the timezone for a container :
– At container start :
docker run --rm -e TZ=Europe/Paris fooImage
– Or in the Dockerfile itself :
ENV TZ=Europe/Paris
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
Timezones list : https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
Execute commands on a container
Usage is docker exec [OPTIONS] CONTAINER COMMAND [ARG...]
Helpful flags :
Options: -d, --detach Detached mode: run command in the background --detach-keys string Override the key sequence for detaching a container -e, --env list Set environment variables -i, --interactive Keep STDIN open even if not attached --privileged Give extended privileges to the command -t, --tty Allocate a pseudo-TTY -u, --user string Username or UID (format: <name|uid>[:<group|gid>]) -w, --workdir string Working directory inside the container |
List containers
The basic command is docker ps
.
Helpful flags :
Options: -a, --all Show all containers (default shows just running) -f, --filter filter Filter output based on conditions provided --format string Pretty-print containers using a Go template -n, --last int Show n last created containers (includes all states) (default -1) -l, --latest Show the latest created container (includes all states) --no-trunc Don't truncate output -q, --quiet Only display numeric IDs -s, --size Display total file sizes |
About the -f or --filter
argument, some helpful filters :
To filter on the image (direct or indirect) name : ancestor=fooImage
To filter on the container name : name=containerName
To filter on the container id : id=containerId
To filter on the container status : status=fooStatus
Where valid values are : created, restarting, running, removing, paused, exited and dead.
Examples :
(Very broad way) To delete all containers which any column contains some specific chars :
docker ps | grep spring-boot-app | awk '{print $1}' | xargs docker -rm -f
(Finer way) Same things but by restricting among x last created containers (ex: 10 here):
docker ps --last 10 | grep spring-boot-app | awk '{print $1}' | xargs docker -rm -f
Inspect docker objects
The inspect command returns low-level information on Docker objects.
It works for any docker objects : images, containers, volumes…
Usage: docker inspect [OPTIONS] NAME|ID [NAME|ID...]
To get in the std out value in a specific format (useful for scripting), we could use the –format (-f) argument :
For example to output the running user of a container such as RunningUser=...
, we could execute :
docker container inspect --format 'RunningUser={{.Config.User}}' my-jenkins
Inspect container
We can also do :
docker container inspect [OPTIONS] CONTAINER
The advantage of that command over the general inspect is the completion ability focused on container only.
Connect/copy to machines/containers
Ssh to the docker machine :
docker-machine ssh
To pass as root :
sudo -i
Run a shell for the container as the default user of the container:
docker exec -it containerId bin/bash
Run a shell for the container as root :
docker exec -it -u root containerId bin/bash
If bash command is not available in the container, we could get an error such as :
OCI runtime exec failed: exec failed: container_linux.go:348: starting container process caused "exec: \"bash\": executable file not found in $PATH": unknown
As workaround, try with sh or without the bin/ folder as prefix :
docker exec -it containerId bin/sh
Copy from a container to the host machine (or the reverse):
docker cp containerId:/myPath pathInTheHost
inspect volumes
List all volumes :
docker volume ls
Inspect a volume :
docker volume inspect volumeName
The data location on the host is provided by the MountPoint attribute.
Run a foo container of the root machine (useful to inspect volume/container content in Windows) :
docker run --rm -it -v /:/vm-root alpine:edge
add the -w /vm-root/var/lib/docker/volumes/
flag to arrive in the volume directory.
Remove containers/volumes
To remove some unused data that is : stopped containers, not used networks, dangling images and dangling build cache :
docker system prune
To remove still further unused data that is : stopped containers, not used networks, images not associated to a container, and all build cache :
docker system prune -a
To remove all containers :
docker rm $(docker stop $(docker ps -aq))
To remove all images :
docker rmi $(docker images -aq)
To remove all volumes :
docker volume rm $(docker volume ls -q)
To remove all exited containers :
docker rm $(docker ps -q -f status=exited)
To remove all dangling images :
docker rmi $(docker images -qf dangling=true)
Remove a specific volume :
docker volume rm volumeName
Log commands
Output logs of a container :
docker logs containerId
Output a specific line count tail and follow next logs of a container :
docker logs --tail 100 -f containerId
Clear logs of a container :
sudo sh -c "truncate -s 0 /var/lib/docker/containers/*/*-json.log"
An alternative is docker system prune
that will clear unused things which logs of stopped containers.
Copy current logs(and not after) of the container in a file :
docker logs containerId &> log.txt
Copy current logs and next as well of the container in a file :
docker logs -f &> your.log &
History commands
Show history of an image (which each layer size):
docker history fooImage
Docker Hosts
Find the static ip of the docker host to allow containers to access/reference it :
ip addr show docker0 | grep -Po 'inet \K[\d.]+'
——————————————————————–
Install manually things in a volume (jenkins example).
Download the application (maven for example):
wget http://www-us.apache.org/dist/maven/maven-3/3.5.4/binaries/apache-maven-3.5.4-bin.tar.gz
Uncompress it into the mounted volume :
tar -xvf apache-maven-3.5.4-bin.tar.gz -C /var/jenkins_home
Create a .bashrc with the updated PATH :
echo "export PATH=/var/jenkins_home/apache-maven-3.5.4/bin:$PATH" > .bashrc
Update the env variable from the .bashrc :
. ~/.bashrc
——————————————————