Use env variables in Dockerfile
You could use args
to meet your requirement.
And one notice here is: you should not use USER
in .env
as a keyword, as it will be override by bash's default environment USER
which will make your dockerfile not get the correct value.
A full workable minimal example as follows, FYI:
docker/Server/Dockerfile:
FROM php:7.3-cli-alpine3.10
ARG USER
ARG PASSWORD
RUN echo ${USER}
RUN echo ${PASSWORD}
.env (NOTE: you had to use USR, not USER here):
USR=user
PASSWORD=password
docker-compose.yaml:
version: '3'
services:
server:
build:
context: .
dockerfile: docker/Server/Dockerfile
args:
- USER=${USR}
- PASSWORD=${PASSWORD}
Execute:
$ docker-compose build --no-cache
Building server
Step 1/5 : FROM php:7.3-cli-alpine3.10
---> 84d7ac5a44d4
Step 2/5 : ARG USER
---> Running in 86b35f6903e2
Removing intermediate container 86b35f6903e2
---> ee6a0e84c76a
Step 3/5 : ARG PASSWORD
---> Running in 92480327a820
Removing intermediate container 92480327a820
---> 1f886e8f6fbb
Step 4/5 : RUN echo ${USER}
---> Running in 8c207c7e6080
user
Removing intermediate container 8c207c7e6080
---> cf97b2cc0317
Step 5/5 : RUN echo ${PASSWORD}
---> Running in 7cbdd909826d
password
Removing intermediate container 7cbdd909826d
---> 6ab7987e080a
Successfully built 6ab7987e080a
Successfully tagged 987_server:latest
The problem here that your ENV
will bem accessed only from run phase not build
.
I suggest you to use build args
for example:
build:
context: .
args:
buildno: 1
gitcommithash: cdc3b19