如何使用Plumber包搭建远程API?解惑本地运行限制问题
Got it, let's sort this out! The default plumber$run() only binds to localhost, which is why you can't access it from remote machines. Here's how to get your API accessible externally:
Bind to all network interfaces
Instead of restricting the API to listen only onlocalhost(127.0.0.1), set thehostparameter to"0.0.0.0". This tells the server to accept connections from any IP address on the network. Here's a quick example:library(plumber) pr <- plumb("your_api_script.R") # Load your API definition file pr$run(host = "0.0.0.0", port = 8000) # Listen on all interfaces, port 8000Open the target port on your server's firewall
Even if your API is listening on0.0.0.0, your server's firewall or cloud provider's security group might block incoming traffic to the port you're using (like 8000). For common setups:- On Linux with
ufw, runsudo ufw allow 8000/tcp - For cloud servers (AWS, GCP, Azure), add an inbound rule in your security group to allow traffic on port 8000 from your desired IP range (or all IPs if you need public access)
- On Linux with
Production-ready upgrade: Use a reverse proxy (e.g., Nginx)
For a stable, production-grade deployment, it's smart to put a reverse proxy in front of your Plumber API. This lets you handle HTTPS, load balancing, and clean domain routing. A basic Nginx config snippet would look like this:server { listen 80; server_name your-api-domain.com; location / { proxy_pass http://localhost:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } }With this setup, users can access your API via
http://your-api-domain.cominstead of needing to specify the port.Keep your API running in the background
To avoid losing access when you close your SSH session, use a process manager likesystemd(Linux) orPM2. For example, asystemdservice file can start your Plumber API automatically on server boot and restart it if it crashes.
内容的提问来源于stack exchange,提问作者Nguyễn Huy Hoàng

