Migrating Databases with Go and Docker-Compose
Running migrations using the golang-migrate tool can help ensure database schema consistency. However, with the deprecation of --network host in Docker-Compose, you may face challenges when executing migrations. This article explores how to adapt to the updated syntax and how to connect to a database residing in a separate container.
Adapt to New Docker-Compose Syntax
To run migrations without --network host, you can 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:
In this configuration, a network called new is created, and the migrate service is linked to the db service through the database alias.
Connecting to a Remote Database
To connect to a database in a separate container, use the following format in the connection string:
"postgres://mydbuser:mydbpwd@database:5432/mydbname?sslmode=disable"
Here, database is the alias defined in the network configuration. This allows you to connect to the remote database as if it were running locally.
The above is the detailed content of How to Run Database Migrations with Go and Docker Compose After the `--network host` Deprecation?. For more information, please follow other related articles on the PHP Chinese website!