Home > Backend Development > Golang > How to Execute One-Time Commands in Docker Compose with Entrypoint Scripts?

How to Execute One-Time Commands in Docker Compose with Entrypoint Scripts?

Susan Sarandon
Release: 2024-11-11 16:57:03
Original
554 people have browsed it

How to Execute One-Time Commands in Docker Compose with Entrypoint Scripts?

How to Execute One-Time Commands in Docker Compose

To set up a Docker environment where a command needs to be executed only once, such as populating a database, a recommended approach is to utilize an entrypoint script.

Entrypoint Script

Create an entrypoint script within your container image, typically named entrypoint.sh. This script will check if the database initialization has been completed, and if not, perform the necessary actions.

Here's an example entrypoint script based on the official WordPress image:

#!/bin/bash

set -e

# Function to check if database initialization is needed
is_init_needed() {
  # Insert database initialization check logic here
  return 0
}

# Check if initialization is needed
if is_init_needed; then
  # Perform database initialization
  echo "Initializing database..."
  /usr/bin/mysql -u "root" -p"$MYSQL_ROOT_PASSWORD" -h "mysql" < /usr/local/init.sql
  echo "Database initialized successfully."
fi

# Start the application
exec "$@"
Copy after login

Docker Compose Configuration

In your docker-compose.yml file, specify the entrypoint script in the entrypoint key for the service that requires initialization, like this:

services:
  my_project:
    build: .
    entrypoint: ["./entrypoint.sh"]
    ...
Copy after login

Additional Notes

  • As mentioned in the answer, using "data-only containers" for Docker volume management is outdated since Docker 1.9. Instead, you can directly attach volumes to services using the volumes key.
  • The entrypoint script should account for the potential that the database container may start after the application container.
  • Docker Compose follows a strict ordering when starting services. The my_project service will not start until its dependencies (mongo and mongodata) are ready.

The above is the detailed content of How to Execute One-Time Commands in Docker Compose with Entrypoint Scripts?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template