Home > Article > Backend Development > How to Execute a Single-Execution Command in Docker Compose During Deployment?
Running Single-Execution Commands in Docker Compose
In order to efficiently deploy a Go web server using Docker Compose, you may encounter a hurdle when attempting to execute a command only once during deployment. This specific command, ./my-project -setup, needs to be run only after your project has been compiled to add essential information to your database.
Docker Compose doesn't provide a direct solution for this need, but you can circumvent it by introducing an entrypoint script to your container. Within this script, you can implement a check to verify if the database has been initialized, and if not, proceed with the required steps.
It's important to note that the order in which containers are started in Docker Compose is not consistent. This means the application container may be started before the database container, potentially leading to database inaccuracies. The entrypoint script should consider this possibility and adjust accordingly.
For instance, you can draw inspiration from the official WordPress image's approach. The image uses an entrypoint script that attempts to establish a connection to the database and conducts the necessary initialization procedures based on the connection status: https://github.com/docker-library/wordpress/blob/df190dc9c5752fd09317d836bd2bdcd09ee379a5/apache/docker-entrypoint.sh#L146-L171.
Additionally, you can simplify your Docker Compose configuration by eliminating the use of a "data-only container" for volume mounting. Since Docker 1.9, Docker supports volume management, including naming volumes. This allows you to exclude the data-only container and modify the Mongo service configuration accordingly:
mongo: image: mongo:latest volumes: - mongodata:/data/db ports: - "28001:27017" command: --smallfiles --rest --auth
This modification will create or reuse a volume named "mongodata." To list or remove volumes, use the commands docker volume ls and docker volume rm
The above is the detailed content of How to Execute a Single-Execution Command in Docker Compose During Deployment?. For more information, please follow other related articles on the PHP Chinese website!