Docker容器未在端口3000上公开Rails应用

时间:2020-06-20 19:09:18

标签: ruby-on-rails docker

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

Docker运行于:

JTextArea diger = new JTextArea(5, 20);

启动服务器:

=> 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://127.0.0.1:3000
Use Ctrl-C to stop

在主机上:

docker run -p 3000:3000 --name railsapp -it 59b54d3bdf48
$ 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

1 个答案:

答案 0 :(得分:2)

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

解决方案是强制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;
    }