Golang-migrate's documentation provides a command for executing all migrations in a given directory:
docker run -v {{ migration dir }}:/migrations --network host migrate/migrate -path=/migrations/ -database postgres://localhost:5432/database up 2
However, this command is not compatible with the syntax of docker-compose. This article will demonstrate how to modify the command to fit the new syntax and connect to a database running in another container.
To integrate golang-migrate with docker-compose, add the following to your docker-compose.yml file:
db: image: postgres networks: new: aliases: - database environment: POSTGRES_DB: mydbname POSTGRES_USER: mydbuser POSTGRES_PASSWORD: mydbpwd ports: - "5432" migrate: image: migrate/migrate networks: - new volumes: - .:/migrations command: ["-path", "/migrations", "-database", "postgres://mydbuser:mydbpwd@database:5432/mydbname?sslmode=disable", "up", "3"] links: - db networks: new:
This configuration creates a network named "new" and includes the "db" and "migrate" services. The "db" service is defined with the required environment variables for a PostgreSQL database.
To connect to a database running in another container, modify the connection string in the "command" attribute of the "migrate" service:
postgres://mydbuser:mydbpwd@database:5432/mydbname?sslmode=disable
In this connection string:
By using the alias "database," you can connect to the "db" service as if it were running on localhost.
With these modifications, you can successfully run golang-migrate with docker-compose and connect to a database in another container.
The above is the detailed content of How to Run Golang-Migrate with Docker Compose and a Separate Database Container?. For more information, please follow other related articles on the PHP Chinese website!