Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dockerfile using variable built using Shell Command

To be more clear on the goal, let's use a better example, say I wanted a portable .env file which collects the host IP address and then uses that inside the build process. The .env file should dynamically generates the variable each build so that if the host IP changes, the build will adjust.

I'm trying to use my host OS version as a build variable for my dockerfile which is called by docker-compose. I also tried just inject the image line into docker-compose to no avail.

Something like this:

cat .env
VER="$(cat /etc/lsb-release | grep -o 'DISTRIB_RELEASE.*' |  cut -f2- -d=)"
#VER=18.04

Dockerfile:

FROM ubuntu:${VER}

or I left that out of dockerfile and used

docker-compose:

image: ubuntu:${VER}
build: .

But i got an error about no build process, not sure it can work this way. Any idea how I would inject a variable built from tools into a docker-file like this? (And/or Docker-Compose for future projects).

Update: I tried the following but continue to get an error.

cat docker-compose.yaml
version: '3.7'

services:
 fileserver:
    container_name: ${CONTAINER_NAME}
    hostname: ${CONTAINER_NAME}
    privileged: true
    build:
      context: .
      args:
        VER: ${VERSION}

......

cat .env
#VERSION="$(cat /etc/lsb-release | grep -o 'DISTRIB_RELEASE.*' |  cut -f2- -d=)"
VERSION="$(cat /etc/lsb-release | grep -o 'DISTRIB_CODENAME.*' |  cut -f2- -d=)"

.......

cat Dockerfile
#ARG VER
#FROM ubuntu:${VER}
FROM ubuntu:bionic

.......

If I uncomment either or both line in the Dockerfile using the variable, I get error:

Step 1/5 : FROM ubuntu:${VER} ERROR: Service 'ubuntu' failed to build: invalid reference format
like image 675
FreeSoftwareServers Avatar asked May 22 '20 04:05

FreeSoftwareServers


1 Answers

ARG is your friend.

  • Dockerfile ARG
  • Docker compose args

Dockerfile

ARG VER=latest
FROM ubuntu:${VER}

The above dockerfile defines a build argument named VER, which is default to latest.

docker-compose.yml

version: '3'
services:
  demo:
    image: enix223/demo
    build:
      context: .
      args:
        VER: ${VERSION}

We substitute image build arg VER with environment variable VERSION.

Start container using shell env variable

VERSION="$(cat /etc/lsb-release | grep -o 'DISTRIB_RELEASE.*' |  cut -f2- -d=)" docker-compose up -d

Start container using .env file

cat > .env << EOF
VERSION="$(cat /etc/lsb-release | grep -o 'DISTRIB_RELEASE.*' |  cut -f2- -d=)"
EOF

docker-compose up -d
like image 133
Enix Avatar answered Oct 11 '22 13:10

Enix