Dockerfile - Use dynamic image name

Hello,

I am using multi-stage builds and I have a case where I would like to use a different image for development vs production, basically, something like:

FROM devilbox/php-fpm:${PHP_VERSION:-"8.2-work"} AS php

where PHP_VERSION would be a ENV var set before calling the docker command.

So far I tried Environment variables in Compose | Docker Documentation but that won’t work in the FROM command. I also tried passing --build-arg to the build command, but same result.

I only had success by doing two different build stages, one for dev and one for production, and reference those in the right docker-compose.yml file, i.e:

# Dockerfile:
FROM devilbox/php-fpm:8.2-work AS php_dev 
...
FROM devilbox/php-fpm:8.2-prod AS php_prod

DEV: docker-compose.override.yml:

  php:
    container_name: php
    build:
      context: .
      target: php_dev

PROD: docker-compose.prod.yml:

  php:
    container_name: php
    build:
      context: .
      target: php_prod

Any idea how to go about this?
Thanks.

It should work like this:

ARG PHP_VERSION=8.2-work
FROM devilbox/php-fpm:${PHP_VERSION} AS php

If PHP_VERSION is not passed as --build-arg, it will fall back to the specified value.
See: Dockerfile reference | Docker Docs for more details.

Yes, you are right, it does work exactly like you explained.
I tried like this before, but most likely I was doing something dumb.
Thank you :wink:

1 Like