Utilizing golang-migrate with Docker Compose for Database Migrations
The golang-migrate documentation recommends using the following command to execute migrations from a specified directory:
docker run -v {{ migration dir }}:/migrations --network host migrate/migrate -path=/migrations/ -database postgres://localhost:5432/database up 2
To adapt this command to the updated docker-compose syntax, which discourages the use of --network, modify your docker-compose.yml file as follows:
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:
To connect to a database residing in another container instead of localhost, a network is established within docker-compose, allowing services to communicate using aliases. In the provided configuration, you can access the db service via the database alias.
The connection string is modified accordingly:
postgres://mydbuser:mydbpwd@database:5432/mydbname?sslmode=disable
With these adjustments, you can successfully execute migrations in golang-migrate with docker-compose, establishing a connection to a database in another container.
The above is the detailed content of How to Use `golang-migrate` with Docker Compose for Database Migrations?. For more information, please follow other related articles on the PHP Chinese website!