首页 > 解决方案 > Docker 容器未在端口 3000 上公开 Rails 应用程序

问题描述

从 docker 容器运行 rails 服务器时,主机无法连接到 http://localhost:3000。

Docker 运行:

docker run -p 3000:3000 --name railsapp -it 59b54d3bdf48

导轨服务器:

=> 引导彪马
=> Rails 6.0.3.1 应用程序开始开发
=> 运行 `rails server --help` 以获得更多启动选项
彪马以单一模式启动...
* 版本 4.3.5 (ruby 2.5.1-p57),代号:神秘旅行者
* 最小线程:5,最大线程:5
* 环境:发展
* 监听 tcp://127.0.0.1:3000
使用 Ctrl-C 停止

从主机:

$ nmap localhost

Starting Nmap 7.60 ( https://nmap.org ) at 2020-06-20 20:59 CEST
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00013s latency).
Not shown: 994 closed ports
PORT     STATE SERVICE
80/tcp   open  http
139/tcp  open  netbios-ssn
445/tcp  open  microsoft-ds
631/tcp  open  ipp
3000/tcp open  ppp
3306/tcp open  mysql

Nmap done: 1 IP address (1 host up) scanned in 0.07 seconds
$ curl http://localhost:3000
curl: (56) Recv failure: Connection reset by peer

标签: ruby-on-railsdocker

解决方案


默认情况下,rails 服务器侦听 IP 127.0.0.1,该 IP 在容器外不可用。

解决方案是强制 rails 服务器监听 0.0.0.0:3000 端口:

# rails s -b 0.0.0.0
=> Booting Puma
=> Rails 6.0.3.1 application starting in development 
=> Run `rails server --help` for more startup options
Puma starting in single mode...
* Version 4.3.5 (ruby 2.5.1-p57), codename: Mysterious Traveller
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://0.0.0.0:3000
Use Ctrl-C to stop

从主机:

$ curl http://localhost:3000
<!DOCTYPE html>
<html>
<head>
  <title>Ruby on Rails</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <style type="text/css" media="screen" charset="utf-8">
    body {
      font-family: Georgia, sans-serif;
      line-height: 2rem;
      font-size: 1.3rem;
      background-color: white;
      margin: 0;
      padding: 0;
      color: #000;
    }

推荐阅读