I have a image defined as follows:
php-enc:
container_name: php-apache
image: php:8.0-apache
volumes:
- ./php/src:/var/www/html/
ports:
- 8000:80
depends_on:
- db
Now i want to run a command inside this container after building this. What I am doing is using the command
docker exec -it php-apache bash
This takes me into the container and I use another command
docker-php-ext-install mysqli
After this mysqli is installed in the php-apache container.
Now I want include all of this into the docker-compose file, So I tried
command: sh -c "docker-php-ext-install mysqli"
php-enc:
container_name: php-apache
image: php:8.0-apache
command: sh -c "docker-php-ext-install mysqli"
volumes:
- ./php/src:/var/www/html/
ports:
- 8000:80
depends_on:
- db
But it is not working. The container stops running
I want to know how to use command in docker-compose.yml
2
Answers
the command in your docker-compose.yml file should like this:
And why your php-apache stopds running, cause’s:
the command:
sh -c "docker-php-ext-install mysqli"
does not remain in foreground process after it’s execution, which is required for the container to remain runningYou should run any installation and setup commands like this in a Dockerfile. This will give you a custom image that contains your application’s dependencies.
The minimal form of this would contain a Dockerfile with just a
FROM
line with your current image name, and thenRUN
any commands you need.Make sure to delete the
image:
line from your Compose file. Leaving it in will apparently work, but replace the actualphp:8.0-apache
image with what you’ve built, which leads to confusing results later.Also consider using the Dockerfile
COPY
directive to include your application code in the image as wellThis will also let you delete the
volumes:
from your Compose file and give you a self-contained runnable image. You could push that image to a registry and run it elsewhere without needing to have a separate copy of the application code. This also would mean that edits on your host system won’t be visible in a container without rebuilding the image (this is a normal workflow in most compiled languages but may not be what you’re used to in PHP).There are other Dockerfile directives like
EXPOSE
andCMD
but you don’t need them here; the information about how to run the main container process gets inherited from the base image.