CLI utilties with Docker
A side discussion popped up today at work around distributing tools via docker images. I thought I’d post up a quick example of how to accomplish this.
app.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def confirm_prompt(question: str) -> bool:
reply = None
while reply not in ("", "y", "n"):
reply = input(f"{question} (Y/n): ").lower()
return (reply in ("", "y"))
reply = confirm_prompt("Are you sure?")
print(reply)
Dockerfile
FROM python:3.9
RUN apt-get update -y && \
apt-get install -y python-pip python-dev
COPY ./requirements.txt /app/requirements.txt
WORKDIR /app
RUN pip install -r requirements.txt
COPY . /app
ENTRYPOINT [ "python" ]
CMD [ "app.py" ]
Build the container image as you normally would:
$ docker build -t example:latest -l example .
Now we can run our custom utility:
$ docker run --rm -it example
Are you sure? (Y/n): y
True
If this is a command we use often then you might consider setting up an alias for your commands:
$ alias exampletool="docker run --rm -it example"
$ exampletool
Are you sure? (Y/n): y
True