Docker CheatSheet

?
R
Bash

Docker most used commands and basic usage. Categories: Docker Daemon, Network, Runtime, Volumes, Arguments, Registry, House Keeping, Shell, Emergency, Miscellaneous

1# Limit the amount of logs (general)
2vi /etc/docker/daemon.json
3```
4{
5    "log-driver": "json-file",
6    "log-opts": {
7        "max-size": "1k",
8        "max-file": "5" 
9    }
10}
11```
12
13# Limit the amount of logs of a container
14docker run --log-opt max-size=1k --log-opt max-file=5 -itd -e POSTGRES_USER=baeldung -e POSTGRES_PASSWORD=baeldung -p 5432:5432
15ls -la var/lib/docker/containers/3eec82654fe6c6ffa579752cc9d1fa034dc34b5533b8672ebe7778449726da32
16
17# Run a Node.js application inside a container
18docker run -v ${PWD}:/app -w /app -p:3600:3600 --env-file .env -it node:14-alpine npm run watch
19
20# Override a crashed container entrypoint and start a bash
21docker run -it --entrypoint /bin/sh my-container:0.1
22
23# Start a container with a volume mount on the local folder
24docker run -v "$(pwd)":/var -it coderecipes/eks-aio:0.1`
25
26# View System Free Space
27docker system df
28
29# Remove unused Images
30// If 5th field is months and the 4th field is higher than 1 month, or (weeks and the 4th is greater than 4), print 3rd (container id)
31echo $(docker images | grep 'coderecipes/client' | awk '$4>1 && $5=="months" || ($4>6 && $5=="weeks") {print $3}')
32docker rmi $(docker images | grep 'coderecipes/client' | awk '$4>1 && $5=="months" || ($4>6 && $5=="weeks") {print $3}')
33
34# New commands V17.*
35docker image ls
36docker container ls
37
38################ Build, Tag and Push ################
39docker login --username foo --password-stdin
40docker build -t rsyslog-server .
41docker tag rsyslog-server coderecipes/rsyslog-server:0.21
42docker push coderecipes/rsyslog-server:0.21
43
44################ Docker Daemon ################
45# Stop and Start Service MacOS
46killall Docker
47open /Applications/Docker.app
48
49# Stop and Start Service Ubuntu
50sudo service stop docker
51sudo service start docker
52
53################ Network ################
54# List docker networks
55docker network ls
56
57# Create network
58docker network create -d=bridge sample
59
60# Start container on a custom private virtual network
61docker run -rm -d --name nginxc --network sample nginx
62
63# View containers attached to networks
64docker network inspect isolated_network
65docker network remove centralizedlogswithdocker_default
66
67## 80/tcp -> 0.0.0.0:3000 (means, TCP port 80 on the container is mapped to all IPV4 Addresses on Port 3000 on the host)
68
69# Map Multiple Ports to random high number ports on host
70EXPOSE 80 2000 2040 4097
71docker run -d -P --name="nginxmulti" nginxmulti
72
73# Change DNS Server
74docker run --dns=8.8.4.4 --name=dnstest network
75
76# Map a port from host to container (h:c)
77docker run -d -p 3000:80 --name="nginx-c1" nginx-img
78
79# Map an IP from host to container
80ifconfig | grep inet
81docker run -d -p 192.168.1.67:2000:80 --name="nginx-c2" nginx-img
82
83# View Port mappings
84docker port nginx-c1
85
86
87################ Run Time ################
88# Runtime commands on Dockerfile
89CMD ['echo', 'hello world'];
90CMD ['ping', '8.8.8.8'];
91
92# Runtime commands from terminal
93docker run -it my_image /bin/bash
94
95
96################ Volumes ################
97# Volume Mount
98## Dockerfile: VOLUME /test-vol ## Warning: a host volume  mount cant be done via Dockerfile
99docker run -it -v /test-vol --name=mycontainer ubuntu /bin/bash
100
101# Host Volume Mount (Recommened only for Dev/QA support machines, or testing purposes)
102docker run -it -v /var/tmp/data:/test-vol --name=telemetry ubuntu /bin/bash
103
104# Re-use an already mounted volume
105docker run -it --volumes-from=other_container ubuntu
106
107# List all Volumes mounted  by the daemon
108docker volume ls
109
110
111################ Arguments ################
112# Pass ENV variables via Dockerfile
113ENV var1=telemetry var2=350
114
115# Pass ENV variables via terminal
116docker run -it nginxdemo6 /bin/bash
117env
118
119# Pass arguments over to the container ENTRYPOINT PID1 via the `docker run command.` 
120ENTRYPOINT ["kubectl"]
121CMD ["get","pods"]  #default values
122
123docker run nginxdemo2 get namespaces #user specified values
124
125
126################ Registry ################
127# Push an image to DockerHub (https://hub.docker.com/r/claudiotx/firstimage/)
128docker tag <image_id> claudiotx/firstimage:0.1
129docker push claudiotx/firstimage:0.1
130
131# Push an image (private registry based on official docker repository image: registry)
132docker images
133docker tag <image_id> registry:5000/image_name
134docker push registry:5000/image_name
135
136
137################ House Keeping ################
138# Remove Images older than 2 weeks
139docker rmi $(docker images | awk '$5=="months" || ($4>2 && $5=="weeks") {print $3,$4,$5}')
140
141# Remove all images
142docker rm -f $(docker ps -a -q)
143
144# Remove images by name
145docker rmi $(docker images |grep 'coderecipes/rsyslog-server')
146
147################ Attach ################
148# Attach to PID1 of a running container
149docker attach 33ebd4876193
150
151# Detach from a container terminal
152CTRL+P+Q
153
154
155################ Emergency ################
156# Copy files from a crashed container
157docker cp <container_id>:/path/to/useful/file /local-path
158
159# Shell access to a crashed container
160docker commit <container_id> my-broken-container &&
161docker run -it my-broken-container /bin/bash
162
163# Metrics about resource usage on the container (memory)
164docker stats <container_id>
165
166# Count Cointainers
167docker ps -a | wc -l
168
169# Remove Multiple Images and Containers
170docker rm $(docker ps -qa --no-trunc --filter "status=exited")
171docker rmi $(docker images --filter "dangling=true" -q --no-trunc)
172
173# Clear Dandling Images and Volumes
174docker images -qf dangling=true | xargs docker rmi
175docker volume ls -qf dangling=true | xargs docker volume rm
176
177# Stream logs from a container
178docker logs 04c8c0d6bd1e -f
179
180# Get all Information from Docker Engine
181docker info
182
183# Check with processes are running on a container (host machine PID tree)
184docker top 04c8c0d6bd1e
185
186# Check with processes are running on a container (container sandboxed PID tree)
187docker attach 04c8c0d6bd1e
188ps -ef
189
190# Docker Images Location
191#Ubuntu:
192ls /var/lib/docker/<storage driver>
193#macOS:
194ls /Users/USERNAME/Library/Containers/com.docker.docker/Data/com.docker.driver.amd64-linux/Docker.qcow2
195
196# Show Last Container which ran
197docker ps -l
198
199# Kill PID1 on the container with a custom signal
200docker kill -s 9 f5f690fc9566
201
202# Full Host Access To CPU Shares
203docker run --cpu-shares=1024 ubuntu
204
205# 1/4 Host Access To CPU Shares
206docker run --cpu-shares=256 ubuntu
207
208# 1GB Host Memory Allocation
209docker run memory=1g
210
211# Run a container detached
212docker run -d ubuntu:17.10 /bin/bash 
213
214# Inspect container
215docker inspect xxxxx
216
217# View top running process on a container
218docker top 3f14a88b86f6
219
220# SSH Access to Docker Linux VM on macOS
221screen ~/Library/Containers/com.docker.docker/Data/com.docker.driver.amd64-linux/tty
222
223# Show Image Layers History
224docker history ubuntu
225
226# Show Docker Configurations for the Host Environment
227docker info
228
229# Create a basic container
230docker run -it centos /bin/bash
231exit
232docker ps -a
233docker start 33ebd4876193
234
235# Create a new image from a modified container
236docker commit 62be12d5015e ubuntu-test1
237docker images
238docker history ubuntu-test1
239
240# Export Docker Image
241docker save -o /tmp/ubuntu-test1.tar ubuntu-test1
242ls -lh /tmp/ubuntu-test1.tar
243
244# Import a Docker Image
245docker load -i /tmp/ubuntu-test1.tar
246docker run -it ubuntu-test1 /bin/bash
247
248################ Miscelaenous ################
249# Restart policy
250docker run --rm -d -p 80:80 --restart=always nginx
251
252# Other commands
253docker images //list all pulled down images
254docker run imagename // create a new instance
255docker run --name node -it npm-install /bin/sh //run an interactive shell
256docker run -d -p 4567:80 --name myName nginx
257docker ps // show running instances
258docker start myContainer
259docker restart myContainer //restart container (usefull when editing source code inside a container)
260docker start -ai myContainer //start a docker container with an interacting console attached (to see console.logs)
261docker stop myContainer
262docker rm myContainer
263docker rmi myImageId
264docker ps -a // list all available instances (by name)
265dokcer images //list all images
266docker pull dockerName //download a docker image from docker hub
267docker pull username/dockerName //download a docker image from the community inside docker hub
268docker run ... -e NODE_ENV=production //set Unix environment variables on the fly
269docker run --name node --it 3ae2d51e9f1c bin/sh
270docker inspect -f "{{ .Mounts }}" mongo
271docker exec CONTAINER ls -lai //view all files inside the container VM
272docker exec -it CONTAINER // start interactive shell on the container VM
273docker exec -it CONTAINER /bin/sh  //virtual shell inside container
274docker logs entry_point --follow --tail 1 //show last log line
275docker build -f MyDockerFile .
276docker build -t npm-install . //build with tag name -use tag later instead of id
277```
278
279FROM ubuntu // sets the container base Linux Distribution
280FROM node:6 //sets the container base Linux to have Node6
281ADD https://www.files.com/myfile /urs/local/bin/ //Downloads and copies a file to the container
282RUN chmod +x /usr/local/bin/dumb-init // Runs a build command, script or process (happens whilst setting up the container --not part of the container)
283exec "$@" //execute all scripts passed over as arguments
284
285Start Interactive Shell on a Stopped Container
286docker run -it 5e8fc6db0da3 /bin/sh
287
288Add Command Alias
289alias my_command='ls -la'
290
291View container log file
292sudo docker inspect redis-server | grep LogPath

Created on 6/14/2017