Docker-Compose Integration for Golang-Migrate
Golang-Migrate facilitates database migration management. To perform all migrations from a directory, the following command is suggested:
docker run -v {{ migration dir }}:/migrations --network host migrate/migrate -path=/migrations/ -database postgres://localhost:5432/database up 2
However, this command does not align with the syntax of the updated docker-compose. This article addresses how to modify this command to fit the newer docker-compose syntax and connect to a database within a different container.
Solution for New Docker-Compose Syntax
The following docker-compose.yml snippet will achieve the desired functionality:
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:
Instead of using the --network host option, a custom network named new is defined. Services within this network can access each other through defined aliases (e.g., accessing the db service via the database alias). This allows you to use the alias as a replacement for localhost in connection strings.
Connection to an External Database
This connection string is used to establish a connection to a database running in a different container:
"postgres://mydbuser:mydbpwd@database:5432/mydbname?sslmode=disable"
In this example, the database alias represents the external database container.
The above is the detailed content of How to Integrate Golang-Migrate with Docker Compose for Database Migrations?. For more information, please follow other related articles on the PHP Chinese website!