当前位置: > > > > 如何使用 docker-compose 运行 golang-migrate?
如何使用 docker-compose 运行 golang-migrate?
来源:stackoverflow
2024-04-19 10:00:34
0浏览
收藏
小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《如何使用 docker-compose 运行 golang-migrate?》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!
问题内容
在 golang-migrate 的文档中,指出您可以运行此命令来在一个文件夹中运行所有迁移。
docker run -v {{ migration dir }}:/migrations --network host migrate/migrate
-path=/migrations/ -database postgres://localhost:5432/database up 2
您将如何执行此操作以适应新 docker-compose 的语法,该语法不鼓励使用 --network?
更重要的是:如何连接到另一个容器中的数据库而不是本地主机中运行的数据库?
解决方案
将其添加到您的 docker-compose.yml 即可解决问题:
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:
您不使用 docker run 的 --network host 选项,而是设置一个名为 new 的网络。该网络内的所有服务都可以通过定义的别名相互访问(在上面的示例中,您可以通过 database 别名访问数据库服务)。然后,您可以使用该别名,就像使用 localhost 一样,即代替 ip 地址。这解释了这个连接字符串:
"postgres://mydbuser:mydbpwd@database:5432/mydbname?sslmode=disable"
从 compose 文件格式版本 2 开始,您无需设置网络。
如 中所述,默认情况下,compose 会为您的应用设置单个网络。服务的每个容器都会加入默认网络,并且可以被该网络上的其他容器访问,并且可以通过与容器名称相同的主机名被它们发现。
所以在你的情况下你可以这样做:
version: '3.8'
services:
#note this databaseservice name is what we will use instead
#of localhost when using migrate as compose assigns
#the service name as host
#for example if we had another container in the same compose
#that wnated to access this service port 2000 we would have written
# databaseservicename:2000
databaseservicename:
image: postgres:13.3-alpine
restart: always
ports:
- "5432"
environment:
POSTGRES_PASSWORD: password
POSTGRES_USER: username
POSTGRES_DB: database
volumes:
- pgdata:/var/lib/postgresql/data
#if we had another container that wanted to access migrate container at let say
#port 1000
#and it's in the same compose file we would have written migrate:1000
migrate:
image: migrate/migrate
depends_on:
- databaseservicename
volumes:
- path/to/you/migration/folder/in/local/computer:/database
# here instead of localhost as the host we use databaseservicename as that is the name we gave to the postgres service
command:
[ "-path", "/database", "-database", "postgres://databaseusername:databasepassword@databaseservicename:5432/database?sslmode=disable", "up" ]
volumes:
pgdata:
以上就是《如何使用 docker-compose 运行 golang-migrate?》的详细内容,更多关于的资料请关注米云公众号!
