Home > Backend Development > Golang > How to Use `golang-migrate` with Docker Compose for Database Migrations?

How to Use `golang-migrate` with Docker Compose for Database Migrations?

Mary-Kate Olsen
Release: 2024-12-21 11:04:16
Original
360 people have browsed it

How to Use `golang-migrate` with Docker Compose for Database Migrations?

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

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

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

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!

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