-1

I have an usecase to get the host IP inside Dockerfile and save it to ENV value, but I am not able to successfully achieve this. Any help is appreciated.

Below is my Sample Dockerfile

FROM maven:3.6.3-openjdk-11
ENV IP=${"`ip -4 route show default | cut -d\" \" -f3`"}
RUN echo $IP
sub
  • 527
  • 1
  • 7
  • 24
  • You mean IP of a hosting machine? – Alexey R. Sep 06 '21 at 16:22
  • @alexey R. Yes.. the above command gives host ip..I understood in Linux,it is always 172.17.0.1.. but I don't want to hard code it.. – sub Sep 06 '21 at 16:40
  • No, that is not always what you think. Host might (and usually do) have several IPs. 127.x.x.x is a loopback IP range, but there are also IPs assigned to network interfaces such as WiFi and ethernet adapters. – Alexey R. Sep 06 '21 at 16:43
  • Ok, agree, so that's also the reason not to hard code it, since as you said it may change. I want to set IP to ENV of Dockerfile. – sub Sep 06 '21 at 16:47
  • Can you add more details on what is the result of your trial? Do you have image built like you are showing and you cannot see that set env when you're inside a container? – Alexey R. Sep 06 '21 at 16:54
  • `failed to solve with frontend dockerfile.v0: failed to create LLB definition: failed to process "${\"`ip -4 route show default | cut -d\\\" \\\" -f3`\"}": missing ':' in su bstitution` I am getting above error. – sub Sep 06 '21 at 17:00
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/236820/discussion-between-sen-and-alexey-r). – sub Sep 06 '21 at 17:03

2 Answers2

1

Evaluating ENV value on build stage is not supported. See the thread here https://github.com/moby/moby/issues/29110

Since your app needs this value on execution phase you can build your image just from

FROM maven:3.6.3-openjdk-11

and then build it like this

docker build -t maven .

and then execute like this:

docker run -ti -e IP=$(ip -4 route show default | cut -d" " -f3) maven /bin/bash

Here is the result visible in container:

root@6856d118d02b:/# echo $IP
192.168.0.1
Alexey R.
  • 8,057
  • 2
  • 11
  • 27
  • Sorry, I think some quotes are missing.. I am getting below error `failed to solve with frontend dockerfile.v0: failed to create LLB definition: Syntax error - can't find = in "-4". Must be of the form: name=value` – sub Sep 06 '21 at 17:02
  • I will check, but I am having some operations with IP inside Dockerfile. So not sure, if this solution suits my need.. – sub Sep 06 '21 at 17:34
  • In this case you can use ARG/--build-arg combination like it is shown here https://stackoverflow.com/a/54887094/8343843 – Alexey R. Sep 06 '21 at 18:11
0

I think Dockerfile just be used to build image,at that time the container IP isn't confirmed。

You can set it in your start.sh or use docker run -e

dianerta
  • 21
  • 3