brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: docker run --cidfile saves the new container's ID to a file

Docker
~/tips/tip-docker-run-cidfile

docker run -d --cidfile /tmp/app.cid nginx

Writes the ID of the container you start into a file, so a script can find it later.

A script that starts a container often needs to talk to it again later. Parsing docker ps output for the right line is fragile. I’d let Docker write the ID down.

docker run -d --cidfile /tmp/app.cid nginx
docker stop "$(cat /tmp/app.cid)"

With --cidfile the full container ID goes into the file you name. It works well in a script or a service wrapper, where the name might not be unique. You can then docker stop, docker logs or docker rm by the contents of that file.

It also adds a bit of safety. Docker refuses to start the container when the file already exists, which stops two runs from sharing a file by accident. So delete the file after you’ve removed the container, or the next run fails.

Caveat: with -d the ID is also printed to the terminal, so you can capture it with id=$(docker run -d ...) and skip the file. The file is the better choice when a different process needs to read the ID later. This one was not run against a live Docker daemon; it follows the Docker documentation, so check it on your own host first.

Further reading: docker run, cidfile

More Docker tips ONBUILD RUN /usr/local/bin/python-build --dir /app/src SHELL ["/bin/bash", "-c"] docker commit <container> myname/testimage:version3 docker import /path/to/exampleimage.tgz docker compose events All Docker tips (192) All topics

Link