Place a function inside the ENV in the Dockerfile

Asked

Viewed 433 times

0

I need to create a Variable that captures the Gateway from the Docker network interface, follow the command:

RUN declare -x SERVER_IP=$(ip route|awk '/default/ { print $3 }')
ENV GATEWAY="$SERVER_IP"
...

During the construction of the Dockerfile it seems that does not work leaving blank, I tried also this way direct:

ENV GATEWAY="$(ip route|awk '/default/ { print $3 }')"

Also nothing, leaving the details I am using the Image Ubuntu:16.04 and before arriving at the variable I have installed the iproute2 for the command ip.

  • when you set the value of GATEWAY using the command ENV of Dockerfile the value of it will remain in the image, but it will not be renewed when you start a container... is that really what you want? it would not be better to take this information in the entrypoint of the image?

  • There is a software that will start through the supervisord, and it looks for this variable in the system but since Docker does not start the init i pecorrir arrow a dynamic variable, in the case of ENTRYPOINT do not know use can give me an example?

  • got a little big... so I wrote a really big reply.

1 answer

1


The command ENV has the idea of defining "static" variables, for example: ENV ENV_TYPE DEV ENV PROD_VERSION 3.1.1

It will not try to process the variable value, it will only accept it as the final value.

For the values that are calculated/recovered at the time of execution it would be better to use ENTRYPOINT or the command CMD to add a script to running the container, that way every time you run docker run suaimage this script will be executed.

Example:

In a folder I have two files: entrypoint.sh and Dockerfile:

  • entrypoint.sh:
#!/bin/sh

export SERVER_IP=$(ip route|awk '/default/ { print $3 }')
echo "SERVER_IP: $SERVER_IP"
  • Dockerfile:
FROM alpine:3.5

ADD entrypoint.sh /

ENTRYPOINT ["/bin/sh", "/entrypoint.sh"]

That way when you do the docker build and docker run the output will be as below:

$ docker build -t test .
Sending build context to Docker daemon 28.67 kB
Step 1/3 : FROM alpine:3.5
 ---> 4a415e366388
Step 2/3 : ADD entrypoint.sh /
 ---> bb398e3cd80a
Removing intermediate container 7d1f1aa2ba81
Step 3/3 : ENTRYPOINT /bin/sh /entrypoint.sh
 ---> Running in 1c71f190fa2e
 ---> f43f141922cf
Removing intermediate container 1c71f190fa2e
Successfully built f43f141922cf
$ docker run test
SERVER_IP: 172.17.0.1

In place of echo "SERVER_IP: $SERVER_IP" must be the specific logic to start the service your container wants to provide.

Documentation about entrypoints: https://docs.docker.com/engine/reference/builder/#entrypoint

Browser other questions tagged

You are not signed in. Login or sign up in order to post.