Home > Mobile >  How to use variable inside of CMD in dockerfile?
How to use variable inside of CMD in dockerfile?

Time:10-04

As you can see in this Dockerfile, I do pass the PORT number as --build-arg at buildtime. Now I need to run npx next start -p ${PORT}:

FROM node:16.6.1-alpine3.14
RUN apk add dumb-init

ARG PORT

EXPOSE $PORT
ENTRYPOINT ["/usr/bin/dumb-init", "--"]
CMD ["npx", "next", "start", "-p", "echo ${PORT}"]

But this is not working. The app is running at the default 3000 port. If I do

CMD ["npx", "next", "start", "-p", "3100"]

The app is running at 3100 as expected. But why can't I use a variable?

CodePudding user response:

The format you are using (exec) won't work. From the docs:

the exec form does not invoke a command shell. This means that normal shell processing does not happen.

Instead, you can execute a shell directly:

CMD ["sh", "-c", "npx next start -p $PORT"]

CodePudding user response:

Setting a env variable and use this in the CMD:

ARG PORT
ENV portValue=$PORT
CMD ["npx", "next", "start", "-p", "${portValue}"]
  • Related