Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 74 additions & 0 deletions DOCUMENTATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -448,13 +448,18 @@ Content-Type: application/json
"ports": {
"80/tcp": "8080"
},
"bind": "loopback",
"volumes": {
"/host/data": "/app/data"
},
"cmd": ["nginx", "-g", "daemon off;"]
}
```

`bind` picks the host interface every published port is bound to. It is
optional and defaults to `"loopback"`; see
[Port publishing and bind addresses](#port-publishing-and-bind-addresses).

Response (201 Created):

```json
Expand Down Expand Up @@ -522,6 +527,75 @@ Authorization: Bearer <token>

Response: 204 No Content

### Port publishing and bind addresses

A container port published to the host is bound to **`127.0.0.1` by default**.
Anything else has to be asked for explicitly, with a `bind` field:

| `bind` | Host IP | Who can reach it |
| ----------------------------- | ---------------- | --------------------------------------------------------------------- |
| `"loopback"` (default) | `127.0.0.1` | This host only — local processes, SSH tunnels, and Ployer's own Caddy |
| `"all_interfaces"` | `0.0.0.0` | Every network the host is on: LAN, any VPN or tailnet, and the public internet if the router forwards the port |
| `{"address": "100.92.195.33"}`| that address | Whoever can route to that interface |

It accepts the field on:

- `POST /api/v1/containers`
- `POST /api/v1/templates/:slug/install` (alongside `expose` and `host_ports`)
- `PUT /api/v1/applications/:id/expose`

Why the default is loopback: Docker publishes through its **own `DOCKER`
iptables chain, which `ufw` does not filter**. A port published on `0.0.0.0` is
reachable from the LAN whether or not a host firewall is configured, and adding
a `ufw` rule afterwards does not close it. For a database that means the
password is the only thing between the network and the data.

The choice is recorded in the stored compose as a three-part port spec, so it
survives a redeploy and can be read back:

```yaml
services:
postgresql:
ports:
- 127.0.0.1:15432:5432 # host-only
- 0.0.0.0:15432:5432 # every interface
```

A two-part spec (`15432:5432`) names no interface and therefore gets the
default. **This is a behaviour change**: services installed before this
existed have two-part specs, so the next redeploy moves them from `0.0.0.0` to
`127.0.0.1`. To keep LAN access, pick "All interfaces" on the application's
page and save — the redeploy writes the interface into the compose explicitly.

Reaching a loopback-bound service from another machine, without republishing
it:

```bash
ssh -L 15432:127.0.0.1:15432 user@ployer-host
```

Applications deployed from git are always loopback-bound on a Docker-assigned
ephemeral port. Caddy runs on the host and proxies to `localhost:<port>`, so
outside traffic arrives through the reverse proxy, which owns 80/443 and TLS.

### Restart policies

A service template's `restart:` is honoured. A template that declares

```yaml
services:
oneshot:
image: busybox
restart: "no"
```

gets Docker's `no` policy, not `unless-stopped`. Accepted values are `no`,
`always`, `unless-stopped` and `on-failure[:max-retries]`; anything else fails
the deploy with an error rather than silently falling back.

A template that declares nothing, and every application deployed from git,
still gets `unless-stopped` so containers come back after a host reboot.

### Network Management

**List networks**
Expand Down
13 changes: 11 additions & 2 deletions crates/ployer-api/src/routes/applications.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ use crate::services::deployment::DeploymentService;
use ployer_core::crypto;
use ployer_core::models::{Application, BuildStrategy};
use ployer_db::repositories::{ApplicationRepository, DeployKeyRepository, EnvVarRepository, SettingsRepository};
use ployer_docker::BindAddress;
use ployer_git::GitService;

pub fn router() -> Router<SharedState> {
Expand Down Expand Up @@ -411,6 +412,10 @@ struct UpdateExposeRequest {
expose: bool,
#[serde(default)]
host_ports: HashMap<u16, u16>,
/// Which host interface to publish on. Defaults to loopback; see
/// `ployer_docker::BindAddress`.
#[serde(default)]
bind: BindAddress,
}

#[derive(Debug, Serialize)]
Expand Down Expand Up @@ -469,8 +474,12 @@ async fn update_expose(
.iter()
.map(|p| (p.container, *req.host_ports.get(&p.container).unwrap_or(&p.container)))
.collect();
new_compose = ployer_templates::compose::add_ports_to_all_services(&new_compose, &bindings)
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
new_compose = ployer_templates::compose::add_ports_to_all_services(
&new_compose,
&bindings,
req.bind.host_ip(),
)
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
}

app_repo
Expand Down
23 changes: 21 additions & 2 deletions crates/ployer-api/src/routes/containers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@ use crate::app_state::SharedState;
use crate::auth::extract_user_id;
use ployer_core::models::AppStatus;
use ployer_db::repositories::ApplicationRepository;
use ployer_docker::{ContainerConfig, ContainerInfo, ContainerStats, NetworkInfo, VolumeInfo};
use ployer_docker::{
BindAddress, ContainerConfig, ContainerInfo, ContainerStats, NetworkInfo, PublishedPort,
VolumeInfo,
};

// Reconcile the owning application's stored status with the container's actual
// state in Docker. The convention is that Ployer-managed containers are named
Expand Down Expand Up @@ -88,10 +91,16 @@ struct CreateContainerRequest {
image: String,
name: Option<String>,
env: Option<Vec<String>>,
/// container_port (e.g. `"80/tcp"`) -> host port. An empty host port lets
/// Docker pick a free ephemeral one.
ports: Option<HashMap<String, String>>,
volumes: Option<HashMap<String, String>>,
network: Option<String>,
cmd: Option<Vec<String>>,
/// Host interface every published port is bound to. Defaults to loopback;
/// see `ployer_docker::BindAddress`.
#[serde(default)]
bind: BindAddress,
}

#[derive(Debug, Serialize)]
Expand Down Expand Up @@ -167,11 +176,21 @@ async fn create_container(
return Err((StatusCode::BAD_REQUEST, "Image name is required".to_string()));
}

// Every published port lands on the same interface — the request carries
// one `bind` for the whole container.
let bind = req.bind.clone();
let config = ContainerConfig {
image: req.image,
name: req.name,
env: req.env,
ports: req.ports,
ports: req.ports.map(|ports| {
ports
.into_iter()
.map(|(container_port, host_port)| {
(container_port, PublishedPort::new(bind.clone(), host_port))
})
.collect()
}),
volumes: req.volumes,
network: req.network,
cmd: req.cmd,
Expand Down
17 changes: 14 additions & 3 deletions crates/ployer-api/src/routes/templates.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use axum::{
Json, Router,
};
use ployer_core::crypto;
use ployer_docker::BindAddress;
use ployer_db::repositories::{ApplicationRepository, EnvVarRepository};
use ployer_templates::{render, Template, TemplateError};
use ployer_templates::render::RenderContext;
Expand Down Expand Up @@ -84,6 +85,13 @@ struct InstallRequest {
/// Map of container_port -> host_port. Only used when `expose` is true.
#[serde(default)]
host_ports: HashMap<u16, u16>,
/// Which host interface to publish on when `expose` is true. Defaults to
/// loopback — `all_interfaces` makes the service reachable from the LAN,
/// from any VPN the host has joined, and from the internet if the router
/// forwards the port, and Docker's publishing is not filtered by a host
/// firewall such as ufw.
#[serde(default)]
bind: BindAddress,
}

#[derive(Debug, Serialize)]
Expand Down Expand Up @@ -136,9 +144,12 @@ async fn install_template(
.iter()
.map(|p| (p.container, *req.host_ports.get(&p.container).unwrap_or(&p.container)))
.collect();
rendered.compose =
ployer_templates::compose::add_ports_to_all_services(&rendered.compose, &bindings)
.map_err(map_err)?;
rendered.compose = ployer_templates::compose::add_ports_to_all_services(
&rendered.compose,
&bindings,
req.bind.host_ip(),
)
.map_err(map_err)?;
}

// Persist application + env vars.
Expand Down
39 changes: 34 additions & 5 deletions crates/ployer-api/src/services/deployment.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use anyhow::{anyhow, Result};
use ployer_core::models::{AppStatus, Application, Deployment, DeploymentStatus, WsEvent};
use ployer_db::repositories::{ApplicationRepository, DeploymentRepository, DomainRepository, EnvVarRepository, SettingsRepository};
use ployer_docker::{DockerClient, ContainerConfig};
use ployer_docker::{BindAddress, DockerClient, ContainerConfig, PublishedPort};
use ployer_git::GitService;
use ployer_proxy::{CaddyClient, RouteSpec};
use sqlx::SqlitePool;
Expand Down Expand Up @@ -277,7 +277,12 @@ impl DeploymentService {
// bind the container's own port (e.g. 80) on the host, or apps
// that EXPOSE 80 collide with each other and with the reverse
// proxy. Caddy is pointed at the assigned port after start.
ports.insert(format!("{}/tcp", p), String::new());
//
// Loopback-bound: Caddy runs on the host and reaches the app
// over localhost, so the published port never has to leave the
// machine. Traffic from outside arrives through Caddy, which
// owns 80/443 and the TLS.
ports.insert(format!("{}/tcp", p), PublishedPort::ephemeral());
ports
}),
volumes: None,
Expand Down Expand Up @@ -562,9 +567,31 @@ impl DeploymentService {

let mut ports_map = HashMap::new();
for port_spec in &service.ports {
if let Some((host, container)) = ployer_templates::compose::split_port(port_spec) {
ports_map.insert(format!("{}/tcp", container), host);
let mapping = ployer_templates::compose::parse_port_spec(port_spec)
.ok_or_else(|| anyhow!("invalid port spec: {port_spec}"))?;
let bind = BindAddress::from_host_ip(mapping.host_ip.as_deref());

// Say out loud, in the deploy log, what the host just published
// and to whom. A compose written before bind addresses existed
// names no interface and so lands on the loopback default.
if bind.is_loopback_only() {
send_log(format!(
"Publishing {} -> {}:{} (this host only)",
mapping.container_port, bind.host_ip(), mapping.host_port
))
.await;
} else {
send_log(format!(
"Warning: publishing {} -> {}:{} — reachable from every network this host is on (LAN, VPN, and the internet if your router forwards it). Docker publishes through its own iptables chain, so a ufw rule will not filter this.",
mapping.container_port, bind.host_ip(), mapping.host_port
))
.await;
}

ports_map.insert(
format!("{}/tcp", mapping.container_port),
PublishedPort::new(bind, mapping.host_port),
);
}
let ports = if ports_map.is_empty() { None } else { Some(ports_map) };

Expand All @@ -579,7 +606,9 @@ impl DeploymentService {
cmd: None,
cpu_limit: application.cpu_limit,
memory_limit: application.memory_limit,
restart: None,
// Honour the template's declared policy. None (the common case)
// still means "unless-stopped".
restart: service.restart.clone(),
};

let container_id = docker.create_container(config).await?;
Expand Down
Loading
Loading