1
votes

When running the rails server from a docker container, the host machine is unable to connect to http://localhost:3000.

Docker runs with:

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

Rails server:

=> 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

From the host machine:

$ 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
1

1 Answers

2
votes

By default, the rails server listens on IP 127.0.0.1 which is not available outside the container.

The solution is to force the rails server to listen port 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

From host machine:

$ 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;
    }