Home > Backend Development > Golang > How to Integrate Golang-Migrate with Docker Compose for Database Migrations?

How to Integrate Golang-Migrate with Docker Compose for Database Migrations?

Barbara Streisand
Release: 2024-12-06 04:05:22
Original
755 people have browsed it

How to Integrate Golang-Migrate with Docker Compose for Database Migrations?

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
Copy after login

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:
Copy after login

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"
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template