Docker Secrets in Environment Variable
How to build your images with docker secrets on your environment variables.
Building Docker Secrets
Build your images with docker secrets on your environment variable(s). Your docker API must be on swarm orchestrator to be able to use docker secrets.
Create your secret password:
printf "dockersecretpassword" | docker secret create dbpw -
Randomize your password (optional, but recommended):
openssl rand -base64 48
Building Images
Build your images by prepping your Dockerfile,entrypoint, and php.
On Dockerfile:
FROM php:8.0-apache
VOLUME /var/www/html
COPY env.php /var/www/html/env.php
COPY env-entrypoint /usr/local/bin/env-entrypoint
RUN chmod +x /usr/local/bin/env-entrypoint
ENTRYPOINT ["env-entrypoint"]
Create env-entrypoint:
#!/usr/bin/env bash
set -e
file_env() {
local var="$1"
local fileVar="${var}_FILE"
local def="${2:-}"
if [ "${!var:-}" ] && [ "${!fileVar:-}" ]; then
echo >&2 "error: both $var and $fileVar are set (but are exclusive)"
exit 1
fi
local val="$def"
if [ "${!var:-}" ]; then
val="${!var}"
elif [ "${!fileVar:-}" ]; then
val="$(< "${!fileVar}")"
fi
export "$var"="$val"
unset "$fileVar"
}
file_env "MYSQL_PASSWORD"
# first arg is `-f` or `--some-option`
if [ "${1#-}" != "$1" ]; then
set -- php "$@"
fi
exec "$@"
Create env.php:
<?php
var_dump($_ENV['MYSQL_PASSWORD']);
Docker Build
Build your docker image and push to your repository.
docker build -t yourimage:latest .
docker push yourimage:latest
Your docker-compose.yml example:
By building your own image, now your password isn't exposed on your docker-compose and it will match your MariaDB that is using docker secrets.
Secrets uses _FILE ending on the environment, followed by /run/secrets/dbpw.
version: '3'
services:
yourimage:
image: yourimage:latest
environment:
MYSQL_PASSWORD_FILE=/run/secrets/dbpw
secrets:
- dbpw
mariadb:
image: mariadb:latest
environment:
MYSQL_PASSWORD_FILE=/run/secrets/dbpw
secrets:
- dbpw
secrets:
dbpw:
external: true
Secured
Now your image is now secured and not exposing valuable login information. If you want to add more secrets into the images, simply add env values on your entrypoint, and php.