loading...

Dynamic Dockerfile with ARG

stevoperisic profile image Stevo Perisic ・1 min read

Sometimes you have a need for a dynamic Dockerfile. For example, you are running a microservice the requires different API calls per environment: dev, staging and production. If your service depends on environment variables to make a distinction of which API to call you usually set those in the Dockerfile using the:

ENV environment=production

That's all fine, however, what do we do if environment needs to change based on the build destination? You would have to manually update the Dockerfile before each build.

We can use the ARG variable instead and update the value of environment ad build time. Consider the following:

ARG environment
ENV environment=${environment:-production} // set a default in case the ARG isn't passed

What we've done above is declared a build argument environment, then used that value to populate the ENV variable environment in the Docker build image. Consider the following build command:

docker build -t myTag --build-arg environment=staging

In this case we first take the value of the build argument, than pass its value down to the ENV variable so that it will evaluate to "staging". However if we don't specify the build arguments and simply run:

docker build -t myTag

Then the value of ENV environment will be "production" as we've set for our default value.

This helps immensely when you have more than 2 environments to build to and have to support different server side renders or API calls that are tightly coupled with those environments.

For more details checkout Docker docs

Thanks!

Discussion

pic
Editor guide