简体   繁体   English

在特定端口上运行 Docker 容器

[英]Running Docker container on a specific port

I have a Rails app deployed with Dokku on DigitalOcean.我在 DigitalOcean 上部署了一个与 Dokku 一起部署的 Rails 应用程序。 I've created a Postgres database and linked it with a Rails app.我创建了一个 Postgres 数据库并将其与 Rails 应用程序链接。 Everything worked fine until I restarted the droplet.一切正常,直到我重新启动液滴。 I figured out that apps stopped working because on restart every Docker container gets a new port and Rails application isn't able to connect to it.我发现应用程序停止工作是因为在重新启动时每个 Docker 容器都会获得一个新端口,而 Rails 应用程序无法连接到它。 If I run dokku postgresql:info myapp it shows the old port, but it has changed.如果我运行dokku postgresql:info myapp它会显示旧端口,但它已更改。 If I manually change database.yml and push it to the dokku repo everything works.如果我手动更改 database.yml 并将其推送到 dokku 存储库,则一切正常。

So how do I prevent Docker from assigning different port each time the server restarts?那么如何防止 Docker 在每次服务器重启时分配不同的端口呢? Or maybe there is an option to change ports of running containers.或者也许可以选择更改正在运行的容器的端口。

I don't have much experience with Dokku but for docker there's no such thing of A container's port.我对 Dokku 没有太多经验,但对于 docker 来说,没有容器端口这样的东西。 In docker you can expose a container's port to receive incoming request and map it to specific ports in your host machine.在 docker 中,您可以公开容器的端口以接收传入请求并将其映射到主机中的特定端口。 With that you can, for instance, run your postgres inside a container and tell docker that you wanna expose the 5432, default postgresql port, to receive incoming requests:例如,你可以在容器中运行你的 postgres 并告诉 docker 你想要公开 5432,默认的 postgresql 端口,以接收传入的请求:

sudo docker run --expose=5432 -P <IMAGE> <COMMAND>

The --expose=5432 tells docker to expose the port 5432 to receive incoming connections from outside world. --expose=5432告诉--expose=5432公开端口 5432 以接收来自外部世界的传入连接。 The -P flag tells docker to map all exposed ports in your container to the host machine's port. -P标志告诉 docker 将容器中所有暴露的端口映射到主机的端口。 with that you can connect to postgres pointing to your host's ip:port.有了它,您可以连接到指向您主机的 ip:port 的 postgres。 If you want to map a container's port to a different host machine port you can use the -p flag:如果要将容器的端口映射到不同的主机端口,可以使用 -p 标志:

sudo docker run --expose=5432 -p=666 <IMAGE> <COMMAND>

Not sure if this can help you with Dokku environment, but I hope so.不确定这是否可以帮助您处理 Dokku 环境,但我希望如此。 For more information about docker's run command see: https://docs.docker.com/reference/commandline/cli/#run有关 docker 的运行命令的更多信息,请参阅: https : //docs.docker.com/reference/commandline/cli/#run

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM