iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article

Fixing Environment Variable Expansion Issues in Dockerfile ENTRYPOINT

に公開

I've been caught by this about three times now, so I'm writing this as a reminder.

Conclusion

Add "sh", "-c" to the ENTRYPOINT and group the command to be executed into a single string. This is because the shell expands environment variables.

ENV PORT=8000
ENV HOST=0.0.0.0

COPY server.py server.py

ENTRYPOINT ["sh", "-c", "/app/.venv/bin/uvicorn server:app --host $HOST --port $PORT"]

Background

I wanted to containerize an API server written in FastAPI and make the port number and host configurable via Docker Compose on the application side. To achieve this, I set environment variables as follows, but the variables were not expanded correctly.

ENV PORT=8000
ENV HOST=0.0.0.0

COPY server.py server.py

ENTRYPOINT ["/app/.venv/bin/uvicorn", "server:app", "--host", "$HOST", "--port", "$PORT"]

Runtime error

Error: Invalid value for '--port': '$PORT' is not a valid integer.
Usage: uvicorn [OPTIONS] APP
Try 'uvicorn --help' for help.

Description in the Official Reference

Unlike the shell form, the exec form does not invoke a command shell. This means that normal shell processing does not happen. For example, ENTRYPOINT [ "echo", "$HOME" ] will not variable expand $HOME. If you want shell processing then either use the shell form or execute a shell directly, for example: ENTRYPOINT [ "sh", "-c", "echo $HOME" ]. When using the exec form and executing a shell directly, as in the case for the shell form, it is the shell that is doing the environment variable expansion, not Docker.

https://docs.docker.com/reference/dockerfile/#entrypoint

Discussion