Docker: Quick tips

Apr 08, 2022

devtip , docker

Run a container locally with an entrypoint

docker run -it ubuntu:latest /bin/bash

Run a container locally as a root or other user with an entrypoint.

# the user must be a valid user on the image
docker run -it -u nobody ubuntu:latest /bin/bash

# useful if root access required to update contents on the image
docker run -it -u root ubuntu:latest /bin/bash

docker exec -it -u root  /bin/bash

Map host path to container path

docker run -v /home/myuser:/home/myuser -it ubuntu:latest /bin/bash

Attach a debugging container to running container in the running container's network

docker run -it --rm --link   alpine sh

Attach a debugging container to running container in the container's PID and namespace with file system level access as well

docker run -it --pid=container: --net=container: --cap-add sys_admin  --cap-add sys_ptrace ubuntu:18.04 /bin/bash

Running container's file system is available in /proc/1/root/ and we can look at running processes from the running container as well from this attached container. This is powerful for debugging issues.

Delete all exited containers

docker rm $(docker ps --filter status=exited -q)

Delete clean up all resources

docker system prune -a

Delete all local images

for image in $(docker image ls | awk '{print $3}');
do
    docker rmi -f ${image};
done

Delete all local volumes

for volume in $(docker volume ls -q);
do
    docker volume rm -f ${volume};
done

Build an image with Dockerfile in current directory, with arguments

docker build --build-arg ARTIFACT_VERSION=0.0.1 -t :0.0.1 .

Export container's filesystem to a tar (hiding all the history and layers, flattening it)

docker export $(docker ps -lq) -o foo.tar

Save container's filesystem to a tar (along with layers and history)

docker save image:tag > /tmp/image.tar

Load container image from tarball (along with layers and history)

docker load -i /tmp/image.tar

JDK 10 and above support consuming % of RAM (container)

The JVM options can be integrated into the Dockerfile in the ENTRYPOINT Java command. But, this will require building another image each time we want to change the values of the JVM options.
A great solution is to integrate this JVM options in the JAVA_OPTS environment variable in the Kubernetes Deployment , which looks like:


...

env:
- name: JAVA_OPTS
  value: "-XX:MinRAMPercentage=20.0 -XX:MaxRAMPercentage=75.0 -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/disk2/dumps"
...

resources: 
    limits:
        memory: 512Mi
    requests:
        memory: 256Mi

...

Links Awards & recognitions Resume Personal Technical Miscellaneous My Blog
 
Last Updated: Apr 08 2022