在golang-migrate的文档中,您可以运行此命令以在一个文件夹中运行所有迁移。
docker run -v {{ migration dir }}:/migrations --network host migrate/migrate
-path=/migrations/ -database postgres://localhost:5432/database up 2
您将如何执行此操作以适应新的docker-compose的语法,从而不鼓励使用--network
?
更重要的是:如何连接到另一个容器中的数据库而不是本地主机中运行的数据库?
答案 0 :(得分:2)
将其添加到您的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:
您建立了一个名为--network host
的网络,而不是使用docker run
的{{1}}选项。该网络内的所有服务都通过定义的别名相互访问(在上例中,您可以通过new
别名访问数据库服务)。然后,您可以像使用database
一样使用该别名,即代替IP地址。这说明了此连接字符串:
localhost
答案 1 :(得分:0)
从 Compose 文件格式版本 2 开始,您无需设置网络。
如 docker networking documentation 中所述,默认情况下,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: