Skip to content

Instantly share code, notes, and snippets.

@AlexAtkinson
Last active January 19, 2024 20:27
Show Gist options
  • Save AlexAtkinson/21d047579247f2e0d14b4382a2faac16 to your computer and use it in GitHub Desktop.
Save AlexAtkinson/21d047579247f2e0d14b4382a2faac16 to your computer and use it in GitHub Desktop.
Docker ProTips

Introduction

This is not a reprint of the docs, but a collection of tips, tricks, and specific guidance for my own reference, and the development of others.

Using

Interactive Container

So long as your container has a CLI, you can access it by specifying 'interactive' and 'tty' (pseudo-tty).

docker run -it alpine:latest /bin/sh

Run an Image Forever

ENTRYPOINT

FROM someimage
ENTRYPOINT ["tail", "-f", "/dev/null"]

Command

 docker run -d alpine tail -f /dev/null

💡 Prefferred overf sleep infinity simply for POSIX portability... But that's hardly a concern these days. ;)

Debugging

General

Be aware of the following useful commands. Use man docker <command> for specifics.

  • man docker <command>
  • docker logs <container id>
  • docker stats <container id>
  • docker cp <container id>:/path/to/file /path/to/local

Inspect

docker inspect can print the entire config, or specifics. See formatting for more. Here's a basic example:

docker inspect -f '{{ .Config.Env}} {{ .Config.Entrypoint}} {{ .Config.Cmd}} {{ .VolumesFrom}} {{.Volumes}}  {{ .HostConfig.links}}' <container_id>

A Quitting Container

Sometimes a container just won't stay alive long enought to diagnose. These commands will copy the unhealthy container to a new image and then connect to it.

docker commit <bad_container_id> my_bad_container
docker run -it my-broken-container /bin/bash

Building

Docker Ignore

Docker Ignore supports Dockerfile specific .dockerignore files, but if it's easy to miss in the docs if go too quickly. Checkout this GIST for a working example.

Dockerfile Examples

Welcome script for every shell

Not every shell picks up /etc/profile, or sources $ENV by default. Add workarounds as necessary.

TODO: Make a sourceable bash script to set this up automatically for a major distro X common shell matrix.

FROM alpine:3

## ENV is only picked up by sh, ash.
##   The welcome script is handled by the .bashrc file for BASH.
ENV ENV="/root/.welcome"

RUN apk update \
      && apk upgrade \
      && apk add --no-cache \
           bash \
           bash-doc \
           bash-completion \
           vim \
           curl

RUN curl -sSL "https://gist.githubusercontent.com/AlexAtkinson/db6059a55da536803b009ffc5a5000d2/raw/welcome.sh?now=$(date +%s)" -o /root/.welcome \
      && echo source /root/.welcome >> /root/.bashrc

CMD ["/bin/bash", "-c", "/root/.welcome ; /usr/bin/tail -f /dev/null"]

Networking

Get Host IP Address

From inside a container, run:

/sbin/ip route|awk '/default/ { print $3 }'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment