sooon
sooon

Reputation: 4878

Docker - Update ENV variable in specific file

I have this Dockerfile:

FROM ubuntu:18.04
USER root
WORKDIR /root/

ENV PORT 3000

COPY ./start.sh /root/
COPY ./pubsubserver /root/

RUN mkdir -p public
ADD public /root/public

CMD ["/root/start.sh"]

and start.sh:

sed -i 's/"port":""/"port":"$PORT"' public/port.json

./pubsubserver --port $PORT

and port.json(before build image and run container):

{
"port":""
}

Basically, when I build the image, pubsubserver, start.sh will be copied to root folder at Docker, and the whole public/ folder will be transferred into root folder at Docker too.

But when I run container:

docker run --name demo -e "PORT=5000"

I can get my pubsubserver getting the port 5000, but my port.json will get:

"port":"$PORT"

which I expect:

"port":"5000"

How can I resolve this?

I read about ENTRYPOINT that might be about to solve this, but I am not sure how to get it to work.

Upvotes: 0

Views: 442

Answers (1)

xdhmoore
xdhmoore

Reputation: 9876

The problem is in your sed line. If your outermost quotes are single quotes, it won't do parameter expansion. I think what you want is something like:

sed -i 's/"port":""/"port":'$PORT'/' public/port.json

However, instead of replacing exactly the string "port":"", why not make it a little more flexible and templatey and replace just a homemade {{PORT}} token:

port.json:

{
"port":"{{PORT}}"
}

sed line:

sed -i "s/{{PORT}}/$PORT/" public/port.json

That way if your json formatting changes it won't break.

Upvotes: 2

Related Questions