Docker-compose has introduced a new syntax that discourages the use of the "--network" option, which raises questions about running migrations using golang-migrate in this environment. This article explores how to set up golang-migrate with docker-compose and connect to a database in another container.
The following command, as stated in the golang-migrate documentation, can be used to run all migrations in one folder:
docker run -v migration-dir:/migrations --network host migrate/migrate -path=/migrations/ -database postgres://localhost:5432/database up 2
To adapt this syntax to docker-compose, we can use the following approach:
Add the following configuration 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 sets up a new network called "new" and adds both the "db" and "migrate" services to it. The "db" service serves as the database, while the "migrate" service is used to run migrations.
Instead of using the "--network host" option, we establish a network and connect to the database via its alias, "database," within that network. This enables the "migrate" service to interact with the "db" service as if it were running on localhost.
The connection string used in the "command" section reflects this connection method:
"postgres://mydbuser:mydbpwd@database:5432/mydbname?sslmode=disable"
Now, running docker-compose up should successfully execute migrations and connect to the database container.
The above is the detailed content of How to Run Golang-Migrate Database Migrations with Docker Compose Without `--network host`?. For more information, please follow other related articles on the PHP Chinese website!