Sometimes I need to access a Rails application in development from another computer, or from a phone, on the same network.
One simple way to achieve this is to start the Rails web server binding it to
0.0.0.0
instead of localhost
.
I can then find the IP address of the computer that's serving the Rails app and access the app from other machines.
Starting the Rails application
In development, I typically start a Rails application with:
bin/dev
This script is already provided by Rails, and by default it starts Foreman using
a Procfile.dev
file for configuration like so:
# ...
exec foreman start -f Procfile.dev "$@"
The Procfile
may list more than one process. In my case, for example, it lists
a web
process and a css
process for watching Tailwind, like so:
# Procfile.dev
web: bin/rails server -p 3000
css: bin/rails tailwindcss:watch
This configuration will, by default, start the Rails server on localhost
.
But I can't access localhost:3000
from other computers on the network.
To have the application accessible from other machines all I have to do is
bind the Rails server to the 0.0.0.0
IP address like so:
# Procfile.dev
web: bin/rails server --binding=0.0.0.0 -p 3000
Once this is done, I just start the Rails in the usual way with:
bin/dev
At this point, the Rails application is accessible from other computers on the network, provided we know the server's IP address.
Find the server's IP address where the application is running
If I don't know the IP address of the originating computer, one way to find it out is by
issuing the hostname -I
command.
This command is run on the server computer, and will output all the IP addresses assigned to the host. The first number should be the one to use to view the Rails application:
$ hostname -I
10.0.0.10 192.168.250.1 10.0.3.1 172.17.0.1 2601:541:e80:550::cf25
Another way to find the IP address is by issuing the arp -a
command to show
all the IP addresses on my network.
This command needs is run on the machine I use to view the Rails app.
The output of the command is something like the list below:
arp -a
_gateway (10.0.0.1) at 80:d0:4a:fb:85:ac [ether] on wlp3s0
? (10.0.0.181) at 40:a9:cf:9a:95:b4 [ether] on wlp3s0
? (10.0.0.10) at 18:cc:18:9d:45:13 [ether] on wlp3s0
? (10.0.0.87) at e0:bb:9e:d9:ba:61 [ether] on wlp3s0
Which one is the IP address to use? I am not sure, but I can look for the correct one by trying each one in turn.
View the Rails application
To access the Rails application, all I have to do now is just type the IP address into the browser, followed by the port the application is running on:
http://10.0.0.10:3000
This should load the application screen in the browser.
This system will also work if I want to view the application from a phone. I just enter the same IP address in the phone browser.
Photo by Caleb Oquendo