Skip to content

An open-source, self-hostable PaaS alternative to Vercel, Heroku & Netlify that lets you easily deploy static sites, databases, full-stack applications and 360+ one-click services on your own servers.

feat(proxy): add custom error pages and resource maintenance mode (#12112)

Andras Bacsai8b30b342387c
diff --git a/app/Actions/Proxy/StartProxy.php b/app/Actions/Proxy/StartProxy.php
index 169064e180..98c0e0bc64 100644
--- a/app/Actions/Proxy/StartProxy.php
+++ b/app/Actions/Proxy/StartProxy.php
@@ -56,10 +56,11 @@ class StartProxy
"echo 'Successfully started coolify-proxy.'",
]);
} else {
- $caddyfile = 'import /dynamic/*.caddy';
+ // The base Caddyfile also holds the maintenance blocks (see Server::caddyBaseCaddyfile()).
+ $caddyfile = base64_encode($server->caddyBaseCaddyfile());
$commands = $commands->merge([
"mkdir -p $proxy_path/dynamic",
- "echo '$caddyfile' | tee $proxy_path/dynamic/Caddyfile > /dev/null",
+ "echo '$caddyfile' | base64 -d | tee $proxy_path/dynamic/Caddyfile > /dev/null",
"echo 'Creating required Docker Compose file.'",
"echo 'Pulling docker image.'",
"docker compose -f $compose_file pull",
diff --git a/app/Actions/Proxy/StopProxy.php b/app/Actions/Proxy/StopProxy.php
index d3999a6e30..881aa0252f 100644
--- a/app/Actions/Proxy/StopProxy.php
+++ b/app/Actions/Proxy/StopProxy.php
@@ -23,11 +23,16 @@ class StopProxy
ProxyStatusChangedUI::dispatch($server->team_id);
}
+ $errorPageCommands = $server->isSwarm() ? [] : [
+ 'docker rm -f '.Server::PROXY_ERROR_PAGE_CONTAINER.' 2>/dev/null || true',
+ ];
+
instant_remote_process(command: [
dockerStopCommand($timeout, $containerName, $server).' 2>/dev/null || true',
"docker rm -f $containerName 2>/dev/null || true",
// The Traefik traffic analytics log rotation sidecar must not outlive the proxy.
'docker rm -f '.TRAEFIK_LOGROTATE_CONTAINER.' 2>/dev/null || true',
+ ...$errorPageCommands,
'# Wait for container to be fully removed',
'for i in {1..10}; do',
" if ! docker ps -a --format \"{{.Names}}\" | grep -q \"^$containerName$\"; then",
diff --git a/app/Actions/Service/StartService.php b/app/Actions/Service/StartService.php
index aacf2bc0cc..be3f0524f6 100644
--- a/app/Actions/Service/StartService.php
+++ b/app/Actions/Service/StartService.php
@@ -8,6 +8,7 @@ use App\Models\Service;
use App\Models\ServiceApplication;
use App\Models\ServiceDatabase;
use Illuminate\Support\Collection;
+use Illuminate\Support\Facades\Log;
use Lorisleiva\Actions\Concerns\AsAction;
use Lorisleiva\Actions\Decorators\JobDecorator;
use Symfony\Component\Yaml\Yaml;
@@ -67,6 +68,14 @@ class StartService
}
}
$commands = array_merge($commands, $this->logDrainNetworkConnectCommands($service));
+ if ($service->is_maintenance_enabled) {
+ // Domains can change with the compose file, so the maintenance routes follow them.
+ try {
+ $service->syncMaintenancePage();
+ } catch (\Throwable $e) {
+ Log::warning('Maintenance page update failed while starting service.', ['service_uuid' => $service->uuid, 'error' => $e->getMessage()]);
+ }
+ }
return remote_process($commands, $service->server, type_uuid: $service->uuid, callEventOnFinish: 'ServiceStartFinished', callEventData: $service->id, queue: deployment_queue());
}
diff --git a/app/Jobs/ApplicationDeploymentJob.php b/app/Jobs/ApplicationDeploymentJob.php
index c8641240cc..f84c77206d 100644
--- a/app/Jobs/ApplicationDeploymentJob.php
+++ b/app/Jobs/ApplicationDeploymentJob.php
@@ -623,6 +623,15 @@ class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueue
\Log::warning('Post deployment command failed for '.$this->deployment_uuid.': '.$e->getMessage());
}
+ // Domains can change with a deployment, so the maintenance routes follow them.
+ if ($this->pull_request_id === 0 && $this->application->is_maintenance_enabled) {
+ try {
+ $this->application->syncMaintenancePage();
+ } catch (Exception $e) {
+ \Log::warning('Maintenance page update failed for '.$this->deployment_uuid.': '.$e->getMessage());
+ }
+ }
+
}
private function deploy_simple_dockerfile()
diff --git a/app/Jobs/DeleteResourceJob.php b/app/Jobs/DeleteResourceJob.php
index 52fa592766..b73c2c5a7a 100644
--- a/app/Jobs/DeleteResourceJob.php
+++ b/app/Jobs/DeleteResourceJob.php
@@ -131,8 +131,21 @@ class DeleteResourceJob implements ShouldBeEncrypted, ShouldQueue
]);
}
+ $maintenanceServers = data_get($this->resource, 'is_maintenance_enabled') ? $this->resource->maintenanceServers() : null;
+
$this->deleteLocalResource();
+ if ($maintenanceServers) {
+ try {
+ // Removes the maintenance route of the deleted resource.
+ $this->resource->syncMaintenancePage($maintenanceServers);
+ } catch (\Throwable $e) {
+ Log::warning('Maintenance page cleanup failed while deleting resource.', [
+ 'resource_id' => $this->resource->id,
+ 'error' => $e->getMessage(),
+ ]);
+ }
+ }
}
private function deleteLocalResource(): void
diff --git a/app/Listeners/ProxyStatusChangedNotification.php b/app/Listeners/ProxyStatusChangedNotification.php
index 9b117d4e13..74851cee52 100644
--- a/app/Listeners/ProxyStatusChangedNotification.php
+++ b/app/Listeners/ProxyStatusChangedNotification.php
@@ -33,6 +33,7 @@ class ProxyStatusChangedNotification implements ShouldQueueAfterCommit
if ($status === 'running') {
$server->setupDefaultRedirect();
+ $server->setupMaintenancePages();
$server->setupDynamicProxyConfiguration();
$server->proxy->force_stop = false;
$server->save();
diff --git a/app/Livewire/Project/Shared/Maintenance.php b/app/Livewire/Project/Shared/Maintenance.php
new file mode 100644
index 0000000000..29c2263e5a
--- /dev/null
+++ b/app/Livewire/Project/Shared/Maintenance.php
@@ -0,0 +1,93 @@
+<?php
+
+namespace App\Livewire\Project\Shared;
+
+use App\Enums\ProxyTypes;
+use App\Models\Application;
+use App\Models\Server;
+use App\Models\Service;
+use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
+use Livewire\Component;
+
+/**
+ * Maintenance mode of an application or service: the proxy shows a maintenance page with
+ * status 503 instead of the resource, and the containers keep running.
+ */
+class Maintenance extends Component
+{
+ use AuthorizesRequests;
+
+ public Application|Service $resource;
+
+ public bool $isMaintenanceEnabled = false;
+
+ public ?string $maintenancePage = null;
+
+ public function mount(): void
+ {
+ $this->isMaintenanceEnabled = (bool) $this->resource->is_maintenance_enabled;
+ $this->maintenancePage = $this->resource->maintenance_page;
+ }
+
+ /**
+ * Servers that run the resource with a supported proxy (Traefik or Caddy, not Swarm).
+ */
+ public function getIsSupportedProperty(): bool
+ {
+ return $this->resource->maintenanceServers()->contains(fn (Server $server) => ! $server->isSwarm()
+ && in_array($server->proxyType(), [ProxyTypes::TRAEFIK->value, ProxyTypes::CADDY->value], true));
+ }
+
+ public function instantSaveMaintenance(): void
+ {
+ try {
+ $this->authorize('update', $this->resource);
+ $this->resource->is_maintenance_enabled = $this->isMaintenanceEnabled;
+ $this->resource->save();
+ $this->resource->syncMaintenancePage();
+ $this->dispatch('success', $this->isMaintenanceEnabled ? 'Maintenance mode enabled.' : 'Maintenance mode disabled.');
+ } catch (\Throwable $e) {
+ $this->isMaintenanceEnabled = (bool) $this->resource->fresh()?->is_maintenance_enabled;
+ handleError($e, $this);
+ }
+ }
+
+ public function submit(): void
+ {
+ try {
+ $this->authorize('update', $this->resource);
+ $this->validate([
+ 'maintenancePage' => ['nullable', 'string', proxyPageSizeRule('maintenance page')],
+ ]);
+ $this->resource->maintenance_page = filled($this->maintenancePage) ? $this->maintenancePage : null;
+ $this->resource->save();
+ if ($this->resource->is_maintenance_enabled) {
+ $this->resource->syncMaintenancePage();
+ }
+ $this->dispatch('success', 'Maintenance page saved.');
+ } catch (\Throwable $e) {
+ handleError($e, $this);
+ }
+ }
+
+ public function resetMaintenancePage(): void
+ {
+ try {
+ $this->authorize('update', $this->resource);
+ $this->resource->maintenance_page = null;
+ $this->resource->save();
+ $this->maintenancePage = null;
+ if ($this->resource->is_maintenance_enabled) {
+ $this->resource->syncMaintenancePage();
+ }
+ $this->dispatch('success', 'Default maintenance page restored.');
+ } catch (\Throwable $e) {
+ handleError($e, $this);
+ }
+ }
+
+ public function render()
+ {
+ return view('livewire.project.shared.maintenance');
+ }
+}
diff --git a/app/Livewire/Server/Proxy.php b/app/Livewire/Server/Proxy.php
index b1a37f4846..6b7a3859e5 100644
--- a/app/Livewire/Server/Proxy.php
+++ b/app/Livewire/Server/Proxy.php
@@ -26,6 +26,8 @@ class Proxy extends Component
public ?string $redirectUrl = null;
+ public ?string $customErrorPage = null;
+
public bool $generateExactLabels = false;
/**
@@ -49,6 +51,7 @@ class Proxy extends Component
return [
'generateExactLabels' => 'required|boolean',
'redirectUrl' => ['nullable', new SafeExternalUrl],
+ 'customErrorPage' => ['nullable', 'string', proxyPageSizeRule('custom error page')],
];
}
@@ -57,6 +60,7 @@ class Proxy extends Component
$this->selectedProxy = $this->server->proxyType();
$this->redirectEnabled = data_get($this->server, 'proxy.redirect_enabled', true);
$this->redirectUrl = data_get($this->server, 'proxy.redirect_url');
+ $this->customErrorPage = $this->server->proxy_error_page;
$this->syncData(false);
$this->clearAppliedTraefikBranchWarning();
}
@@ -187,6 +191,20 @@ class Proxy extends Component
}
}
+ public function resetCustomErrorPage(): void
+ {
+ try {
+ $this->authorize('update', $this->server);
+ $this->server->proxy_error_page = null;
+ $this->server->save();
+ $this->customErrorPage = null;
+ $this->server->setupDefaultRedirect();
+ $this->dispatch('success', 'Default error page restored.');
+ } catch (\Throwable $e) {
+ handleError($e, $this);
+ }
+ }
+
public function submit()
{
try {
@@ -194,6 +212,7 @@ class Proxy extends Component
$this->validate();
SaveProxyConfiguration::run($this->server, $this->proxySettings);
$this->server->proxy->redirect_url = $this->redirectUrl;
+ $this->server->proxy_error_page = filled($this->customErrorPage) ? $this->customErrorPage : null;
$this->server->save();
auditLog('ui.server.proxy.configuration_saved', $this->proxyAuditContext());
$this->server->setupDefaultRedirect();
diff --git a/app/Models/Application.php b/app/Models/Application.php
index 2d6f3fbfa0..8a65051c66 100644
--- a/app/Models/Application.php
+++ b/app/Models/Application.php
@@ -17,6 +17,7 @@ use App\Traits\Auditable;
use App\Traits\ClearsGlobalSearchCache;
use App\Traits\HasComposeVolumeWarnings;
use App\Traits\HasConfiguration;
+use App\Traits\HasMaintenancePage;
use App\Traits\HasMetrics;
use App\Traits\HasNoindexDomains;
use App\Traits\HasSafeStringAttribute;
@@ -137,7 +138,7 @@ use Symfony\Component\Yaml\Yaml;
class Application extends BaseModel
{
/** @use HasFactory<ApplicationFactory> */
- use Auditable, ClearsGlobalSearchCache, HasComposeVolumeWarnings, HasConfiguration, HasFactory, HasMetrics, HasNoindexDomains, HasSafeStringAttribute, HasSecretManager, ReleasesManagedDnsRecords, SoftDeletes;
+ use Auditable, ClearsGlobalSearchCache, HasComposeVolumeWarnings, HasConfiguration, HasFactory, HasMaintenancePage, HasMetrics, HasNoindexDomains, HasSafeStringAttribute, HasSecretManager, ReleasesManagedDnsRecords, SoftDeletes;
public const MAX_DOCKER_COMPOSE_SIZE_BYTES = 5 * 1024 * 1024;
@@ -290,6 +291,7 @@ class Application extends BaseModel
'restart_limit_reached' => 'boolean',
'container_present' => 'boolean',
'last_restart_at' => 'datetime',
+ 'is_maintenance_enabled' => 'boolean',
];
}
@@ -585,6 +587,39 @@ class Application extends BaseModel
instant_remote_process(["docker network rm {$uuid}"], $server, false);
}
+ /**
+ * Domains of the application, or of every service of a Docker Compose application.
+ *
+ * @return Collection<int, array{url: string, force_https: bool}>
+ */
+ public function maintenanceDomains(): Collection
+ {
+ if ($this->build_pack === 'dockercompose') {
+ $urls = collect(json_decode($this->docker_compose_domains ?: '[]', true) ?: [])
+ ->flatMap(fn ($service) => explode(',', (string) data_get($service, 'domain', '')));
+ } else {
+ $urls = collect($this->fqdns);
+ }
+ $forceHttps = (bool) $this->isForceHttpsEnabled();
+
+ return $urls->map(fn ($url) => trim((string) $url))
+ ->filter()
+ ->map(fn (string $url) => ['url' => $url, 'force_https' => $forceHttps])
+ ->values();
+ }
+
+ /**
+ * @return Collection<int, Server>
+ */
+ public function maintenanceServers(): Collection
+ {
+ return collect([$this->destination?->server])
+ ->concat($this->additional_servers)
+ ->filter()
+ ->unique('id')
+ ->values();
+ }
+
public function additional_servers()
{
return $this->belongsToMany(Server::class, 'additional_destinations')
diff --git a/app/Models/Server.php b/app/Models/Server.php
index bc20bc07b8..3ab35001f2 100644
--- a/app/Models/Server.php
+++ b/app/Models/Server.php
@@ -130,6 +130,19 @@ class Server extends BaseModel
public const PLACEHOLDER_IPS = [self::PLACEHOLDER_IP, '0.0.0.0', '::'];
+ /**
+ * Serves the proxy error pages (503.html) for the Traefik and Caddy catch-all.
+ */
+ public const PROXY_ERROR_PAGE_CONTAINER = 'coolify-proxy-error-pages';
+
+ public const PROXY_ERROR_PAGE_IMAGE = 'busybox:musl';
+
+ /**
+ * Maximum size of a custom error or maintenance page. The page goes to the server with scp
+ * (see uploadProxyFile()), so this limit only keeps the Livewire payload reasonable.
+ */
+ public const PROXY_ERROR_PAGE_MAX_BYTES = 1048576;
+
/**
* Default Caddy proxy image. caddy-docker-proxy 2.13 ships Caddy 2.11.
*/
@@ -325,6 +338,7 @@ class Server extends BaseModel
protected $hidden = [
'logdrain_axiom_api_key',
'logdrain_newrelic_license_key',
+ 'proxy_error_page',
];
protected $schemalessAttributes = [
@@ -645,6 +659,10 @@ class Server extends BaseModel
return $this->proxyType() && $this->proxyType() !== 'NONE' && $this->isFunctional() && ! $this->isSwarmWorker() && $this->canHostResources();
}
+ /**
+ * Writes the catch-all proxy configuration for requests that no resource handles.
+ * Priority: redirect URL > custom error page > Coolify default error page.
+ */
public function setupDefaultRedirect()
{
$banner =
@@ -653,7 +671,6 @@ class Server extends BaseModel
$dynamic_conf_path = $this->proxyPath().'/dynamic';
$proxy_type = $this->proxyType();
$redirect_enabled = $this->proxy->redirect_enabled ?? true;
- $redirect_url = $this->proxy->redirect_url;
if ($proxy_type === ProxyTypes::TRAEFIK->value) {
$default_redirect_file = "$dynamic_conf_path/default_redirect_503.yaml";
} elseif ($proxy_type === ProxyTypes::CADDY->value) {
@@ -665,76 +682,364 @@ class Server extends BaseModel
"rm -f $dynamic_conf_path/default_redirect_404.yaml",
"rm -f $dynamic_conf_path/default_redirect_404.caddy",
], $this);
+ // The error page container must run before the catch-all points to it.
+ $this->setupProxyErrorPageContainer();
if ($redirect_enabled === false) {
instant_remote_process(["rm -f $default_redirect_file"], $this);
} else {
- if ($proxy_type === ProxyTypes::CADDY->value) {
- if (filled($redirect_url)) {
- $conf = ":80, :443 {
+ $conf = $banner.$this->defaultRedirectConfiguration();
+ $base64 = base64_encode($conf);
+ instant_remote_process([
+ "echo '$base64' | base64 -d | tee $default_redirect_file > /dev/null",
+ ], $this);
+ }
+
+ if ($proxy_type === 'CADDY') {
+ $this->reloadCaddy();
+ }
+ }
+
+ /**
+ * Catch-all proxy configuration (without the banner) for an enabled default redirect.
+ */
+ public function defaultRedirectConfiguration(): string
+ {
+ $redirect_url = $this->proxy->redirect_url;
+ $usesErrorPage = $this->usesProxyErrorPage();
+
+ if ($this->proxyType() === ProxyTypes::CADDY->value) {
+ if (filled($redirect_url)) {
+ return ":80, :443 {
redir $redirect_url
}";
- } else {
- $conf = ':80, :443 {
+ }
+ if ($usesErrorPage) {
+ // busybox httpd answers 200, so copy_response sets the 503 status.
+ return ':80, :443 {
+ reverse_proxy '.self::PROXY_ERROR_PAGE_CONTAINER.':80 {
+ rewrite /503.html
+ handle_response {
+ copy_response 503
+ }
+ }
+}';
+ }
+
+ return ':80, :443 {
respond 503
}';
- }
- } elseif ($proxy_type === ProxyTypes::TRAEFIK->value) {
- $dynamic_conf = [
- 'http' => [
- 'routers' => [
- 'catchall' => [
- 'entryPoints' => [
- 0 => 'http',
- 1 => 'https',
- ],
- 'service' => 'noop',
- 'rule' => 'PathPrefix(`/`)',
- 'tls' => [
- 'certResolver' => 'letsencrypt',
- ],
- 'priority' => -1000,
- ],
+ }
+
+ $dynamic_conf = [
+ 'http' => [
+ 'routers' => [
+ 'catchall' => [
+ 'entryPoints' => [
+ 0 => 'http',
+ 1 => 'https',
],
- 'services' => [
- 'noop' => [
- 'loadBalancer' => [
- 'servers' => [],
- ],
- ],
+ 'service' => 'noop',
+ 'rule' => 'PathPrefix(`/`)',
+ 'tls' => [
+ 'certResolver' => 'letsencrypt',
],
+ 'priority' => -1000,
],
- ];
- if (filled($redirect_url)) {
- $dynamic_conf['http']['routers']['catchall']['middlewares'] = [
- 0 => 'redirect-regexp',
- ];
-
- $dynamic_conf['http']['services']['noop']['loadBalancer']['servers'][0] = [
- 'url' => '',
- ];
- $dynamic_conf['http']['middlewares'] = [
- 'redirect-regexp' => [
- 'redirectRegex' => [
- 'regex' => '(.*)',
- 'replacement' => $redirect_url,
- 'permanent' => false,
- ],
+ ],
+ 'services' => [
+ 'noop' => [
+ 'loadBalancer' => [
+ 'servers' => [],
],
- ];
+ ],
+ ],
+ ],
+ ];
+ if (filled($redirect_url)) {
+ $dynamic_conf['http']['routers']['catchall']['middlewares'] = [
+ 0 => 'redirect-regexp',
+ ];
+
+ $dynamic_conf['http']['services']['noop']['loadBalancer']['servers'][0] = [
+ 'url' => '',
+ ];
+ $dynamic_conf['http']['middlewares'] = [
+ 'redirect-regexp' => [
+ 'redirectRegex' => [
+ 'regex' => '(.*)',
+ 'replacement' => $redirect_url,
+ 'permanent' => false,
+ ],
+ ],
+ ];
+ } elseif ($usesErrorPage) {
+ // The noop service (no servers) keeps the 503; the errors middleware only replaces the body.
+ $dynamic_conf['http']['routers']['catchall']['middlewares'] = [
+ 0 => 'error-pages',
+ ];
+ $dynamic_conf['http']['middlewares'] = [
+ 'error-pages' => [
+ 'errors' => [
+ 'status' => ['503'],
+ 'service' => 'error-pages',
+ 'query' => '/503.html',
+ ],
+ ],
+ ];
+ $dynamic_conf['http']['services']['error-pages'] = [
+ 'loadBalancer' => [
+ 'servers' => [
+ ['url' => 'http://'.self::PROXY_ERROR_PAGE_CONTAINER.':80'],
+ ],
+ ],
+ ];
+ }
+
+ // A router with `tls` matches only HTTPS, so plain HTTP needs its own catch-all router.
+ if (! $this->isSwarm()) {
+ $catchall = $dynamic_conf['http']['routers']['catchall'];
+ $dynamic_conf['http']['routers']['catchall']['entryPoints'] = ['https'];
+ unset($catchall['tls']);
+ $dynamic_conf['http']['routers']['catchall-http'] = array_merge($catchall, ['entryPoints' => ['http']]);
+ }
+
+ return Yaml::dump($dynamic_conf, 12, 2);
+ }
+
+ /**
+ * True when the catch-all shows the error page: a standalone Traefik or Caddy proxy with
+ * the default redirect enabled and no redirect URL. Swarm servers keep the plain 503.
+ */
+ public function usesProxyErrorPage(): bool
+ {
+ return ! $this->isSwarm()
+ && in_array($this->proxyType(), [ProxyTypes::TRAEFIK->value, ProxyTypes::CADDY->value], true)
+ && ($this->proxy->redirect_enabled ?? true) !== false
+ && blank($this->proxy->redirect_url);
+ }
+
+ public function proxyErrorPagesPath(): string
+ {
+ return base_configuration_dir().'/proxy/error-pages';
+ }
+
+ /**
+ * The custom error page HTML, or the Coolify default page.
+ */
+ public function proxyErrorPageHtml(): string
+ {
+ return filled($this->proxy_error_page) ? $this->proxy_error_page : view('proxy.error-page')->render();
+ }
+
+ /**
+ * Applications and services on this server that are in maintenance mode.
+ *
+ * @return Collection<int, Application|Service>
+ */
+ public function maintenanceResources(): Collection
+ {
+ if ($this->isSwarm() || ! in_array($this->proxyType(), [ProxyTypes::TRAEFIK->value, ProxyTypes::CADDY->value], true)) {
+ return collect();
+ }
+
+ return $this->applications()->where('is_maintenance_enabled', true)->values()
+ ->concat($this->services()->where('is_maintenance_enabled', true)->get());
+ }
+
+ /**
+ * Writes 503.html and starts the error page container, or removes the container when
+ * neither the catch-all nor a maintenance page uses it. Swarm servers are not supported.
+ */
+ public function setupProxyErrorPageContainer(): void
+ {
+ if ($this->isSwarm()) {
+ return;
+ }
+
+ $container = self::PROXY_ERROR_PAGE_CONTAINER;
+ if (! $this->usesProxyErrorPage() && $this->maintenanceResources()->isEmpty()) {
+ instant_remote_process(["docker rm -f $container >/dev/null 2>&1 || true"], $this);
+
+ return;
+ }
+
+ $path = $this->proxyErrorPagesPath();
+ $mount = devHostDockerPath($this, $path);
+ $restart = RESTART_MODE;
+
+ instant_remote_process(["mkdir -p $path"], $this);
+ $this->uploadProxyFile("$path/503.html", $this->proxyErrorPageHtml());
+ instant_remote_process([
+ dockerNetworkEnsureCommand('coolify'),
+ "docker start $container >/dev/null 2>&1 || docker run -d --name $container --network coolify --restart $restart --label coolify.managed=true -v $mount:/www:ro ".self::PROXY_ERROR_PAGE_IMAGE.' httpd -f -p 80 -h /www',
+ // A proxy on custom networks only must still reach the error page container.
+ 'docker network connect coolify coolify-proxy >/dev/null 2>&1 || true',
+ ], $this);
+ }
+
+ /**
+ * Writes $contents to $path on this server with scp. A shell command is limited to 128 KiB,
+ * so large pages and proxy files cannot go inside one command.
+ */
+ public function uploadProxyFile(string $path, string $contents): void
+ {
+ $uploadPath = '/tmp/coolify-upload-'.bin2hex(random_bytes(8));
+ $localPath = tempnam(sys_get_temp_dir(), 'coolify-proxy-file-');
+ try {
+ file_put_contents($localPath, $contents);
+ instant_scp($localPath, $uploadPath, $this);
+ } finally {
+ @unlink($localPath);
+ }
+
+ // The proxy and the page container read the file as root, other users do not need it.
+ instant_remote_process(["mv -f $uploadPath $path", "chmod 644 $path"], $this);
+ }
+
+ /**
+ * Writes the maintenance pages and the proxy configuration that shows them instead of the
+ * applications and services in maintenance mode. Swarm servers are not supported.
+ */
+ public function setupMaintenancePages(): void
+ {
+ $proxyType = $this->proxyType();
+ if ($this->isSwarm() || ! in_array($proxyType, [ProxyTypes::TRAEFIK->value, ProxyTypes::CADDY->value], true)) {
+ return;
+ }
+
+ $resources = $this->maintenanceResources();
+ $path = $this->proxyErrorPagesPath();
+ $keep = $resources->map(fn ($resource) => "! -name '{$resource->maintenancePageFile()}' ")->implode('');
+
+ instant_remote_process([
+ "mkdir -p $path",
+ "find $path -maxdepth 1 -name 'maintenance-*.html' {$keep}-delete",
+ ], $this);
+ $this->setupProxyErrorPageContainer();
+
+ foreach ($resources as $resource) {
+ $this->uploadProxyFile("$path/{$resource->maintenancePageFile()}", $resource->maintenancePageHtml());
+ }
+
+ $dynamicPath = $this->proxyPath().'/dynamic';
+ instant_remote_process(["mkdir -p $dynamicPath"], $this);
+ if ($proxyType === ProxyTypes::TRAEFIK->value) {
+ $file = "$dynamicPath/coolify-maintenance.yaml";
+ $configuration = $this->maintenanceTraefikConfiguration($resources);
+ if ($configuration === null) {
+ instant_remote_process(["rm -f $file"], $this);
+ } else {
+ $this->uploadProxyFile($file, $configuration);
+ }
+ } else {
+ // caddy-docker-proxy reads the base Caddyfile again on its next poll.
+ $this->uploadProxyFile("$dynamicPath/Caddyfile", $this->caddyBaseCaddyfile($resources));
+ }
+ }
+
+ /**
+ * Traefik routers that use the same rule as the resource routers, with a priority one
+ * higher. Traefik uses the rule length as the default priority, so a resource on a longer
+ * path of the same host keeps its own router.
+ *
+ * @param Collection<int, Application|Service> $resources
+ */
+ public function maintenanceTraefikConfiguration(Collection $resources): ?string
+ {
+ $routers = [];
+ $middlewares = [];
+ foreach ($resources as $resource) {
+ $routes = $resource->maintenanceRoutes();
+ if ($routes->isEmpty()) {
+ continue;
+ }
+ $middleware = "coolify-maintenance-{$resource->uuid}";
+ $middlewares[$middleware] = [
+ 'errors' => [
+ 'status' => ['503'],
+ 'service' => 'coolify-maintenance-pages',
+ 'query' => '/'.$resource->maintenancePageFile(),
+ ],
+ ];
+ foreach ($routes as $index => $route) {
+ $rule = "Host(`{$route['host']}`) && PathPrefix(`{$route['path']}`)";
+ $router = [
+ 'entryPoints' => ['http'],
+ 'rule' => $rule,
+ 'service' => 'coolify-maintenance-noop',
+ 'middlewares' => ['coolify-maintenance-headers', $middleware],
+ 'priority' => strlen($rule) + 1,
+ ];
+ $routers["coolify-maintenance-{$resource->uuid}-{$index}-http"] = $router;
+ if ($route['scheme'] === 'https') {
+ $routers["coolify-maintenance-{$resource->uuid}-{$index}-https"] = array_merge($router, [
+ 'entryPoints' => ['https'],
+ 'tls' => ['certResolver' => 'letsencrypt'],
+ ]);
}
- $conf = Yaml::dump($dynamic_conf, 12, 2);
}
- $conf = $banner.$conf;
- $base64 = base64_encode($conf);
- instant_remote_process([
- "echo '$base64' | base64 -d | tee $default_redirect_file > /dev/null",
- ], $this);
}
- if ($proxy_type === 'CADDY') {
- $this->reloadCaddy();
+ if ($routers === []) {
+ return null;
+ }
+
+ $middlewares['coolify-maintenance-headers'] = [
+ 'headers' => ['customResponseHeaders' => ['Retry-After' => '300']],
+ ];
+
+ return "# This file is generated by Coolify, do not edit it manually.\n\n".Yaml::dump([
+ 'http' => [
+ 'routers' => $routers,
+ 'middlewares' => $middlewares,
+ 'services' => [
+ // No servers: Traefik answers 503 and the errors middleware adds the page.
+ 'coolify-maintenance-noop' => ['loadBalancer' => ['servers' => []]],
+ 'coolify-maintenance-pages' => [
+ 'loadBalancer' => ['servers' => [['url' => 'http://'.self::PROXY_ERROR_PAGE_CONTAINER.':80']]],
+ ],
+ ],
+ ],
+ ], 12, 2);
+ }
+
+ /**
+ * The base Caddyfile of caddy-docker-proxy. A maintenance block uses the same site address
+ * as the resource labels, so caddy-docker-proxy merges both into one site block. Its named
+ * matcher has the same path as the resource handle, so Caddy runs it first.
+ *
+ * @param Collection<int, Application|Service>|null $resources
+ */
+ public function caddyBaseCaddyfile(?Collection $resources = null): string
+ {
+ $resources ??= $this->maintenanceResources();
+ $sites = [];
+ foreach ($resources as $resource) {
+ foreach ($resource->maintenanceRoutes() as $index => $route) {
+ $address = caddySiteAddress($route['scheme'], $route['host'], $route['force_https']);
+ $matcher = "@coolify-maintenance-{$resource->uuid}-{$index}";
+ $sites[$address][] = implode("\n", [
+ "\t{$matcher} path {$route['path']}*",
+ "\thandle {$matcher} {",
+ "\t\treverse_proxy ".self::PROXY_ERROR_PAGE_CONTAINER.':80 {',
+ "\t\t\trewrite /{$resource->maintenancePageFile()}",
+ "\t\t\theader_down Retry-After 300",
+ "\t\t\thandle_response {",
+ "\t\t\t\tcopy_response 503",
+ "\t\t\t}",
+ "\t\t}",
+ "\t}",
+ ]);
+ }
}
+
+ $caddyfile = 'import /dynamic/*.caddy';
+ foreach ($sites as $address => $blocks) {
+ $caddyfile .= "\n\n{$address} {\n".implode("\n", $blocks)."\n}";
+ }
+
+ return $caddyfile."\n";
}
public function setupDynamicProxyConfiguration()
diff --git a/app/Models/Service.php b/app/Models/Service.php
index c5ddeb5941..d823f0f9f0 100644
--- a/app/Models/Service.php
+++ b/app/Models/Service.php
@@ -9,6 +9,7 @@ use App\Support\ResourceStartActivity;
use App\Traits\Auditable;
use App\Traits\ClearsGlobalSearchCache;
use App\Traits\HasComposeVolumeWarnings;
+use App\Traits\HasMaintenancePage;
use App\Traits\HasSafeStringAttribute;
use App\Traits\HasSecretManager;
use Illuminate\Database\Eloquent\Casts\Attribute;
@@ -45,7 +46,7 @@ use Symfony\Component\Yaml\Yaml;
)]
class Service extends BaseModel
{
- use Auditable, ClearsGlobalSearchCache, HasComposeVolumeWarnings, HasFactory, HasSafeStringAttribute, HasSecretManager, SoftDeletes;
+ use Auditable, ClearsGlobalSearchCache, HasComposeVolumeWarnings, HasFactory, HasMaintenancePage, HasSafeStringAttribute, HasSecretManager, SoftDeletes;
private static $parserVersion = '5';
@@ -79,6 +80,13 @@ class Service extends BaseModel
'docker_compose_raw',
];
+ protected function casts(): array
+ {
+ return [
+ 'is_maintenance_enabled' => 'boolean',
+ ];
+ }
+
protected static function booted()
{
static::creating(function ($service) {
@@ -1516,6 +1524,29 @@ class Service extends BaseModel
return $this->hasMany(ServiceApplication::class);
}
+ /**
+ * Domains of every application in the service stack.
+ *
+ * @return Collection<int, array{url: string, force_https: bool}>
+ */
+ public function maintenanceDomains(): Collection
+ {
+ return $this->applications()->get()
+ ->flatMap(fn (ServiceApplication $application) => collect($application->fqdns)
+ ->map(fn ($url) => trim((string) $url))
+ ->filter()
+ ->map(fn (string $url) => ['url' => $url, 'force_https' => $application->isForceHttpsEnabled()]))
+ ->values();
+ }
+
+ /**
+ * @return Collection<int, Server>
+ */
+ public function maintenanceServers(): Collection
+ {
+ return collect([$this->server])->filter()->values();
+ }
+
public function databases()
{
return $this->hasMany(ServiceDatabase::class);
diff --git a/app/Traits/HasMaintenancePage.php b/app/Traits/HasMaintenancePage.php
new file mode 100644
index 0000000000..ed5b9d3827
--- /dev/null
+++ b/app/Traits/HasMaintenancePage.php
@@ -0,0 +1,85 @@
+<?php
+
+namespace App\Traits;
+
+use App\Models\Server;
+use Illuminate\Support\Collection;
+use Spatie\Url\Url;
+
+/**
+ * Maintenance mode for a resource with domains: the proxy shows a maintenance page with
+ * status 503 instead of the resource. The resource containers keep running.
+ *
+ * @property bool $is_maintenance_enabled
+ * @property string|null $maintenance_page
+ */
+trait HasMaintenancePage
+{
+ /**
+ * @return Collection<int, array{url: string, force_https: bool}>
+ */
+ abstract public function maintenanceDomains(): Collection;
+
+ /**
+ * @return Collection<int, Server>
+ */
+ abstract public function maintenanceServers(): Collection;
+
+ /**
+ * Proxy routes for the maintenance page. Domains go into the Traefik and Caddy configuration
+ * as plain text, so a domain with an unexpected host or path is skipped.
+ *
+ * @return Collection<int, array{scheme: string, host: string, path: string, force_https: bool}>
+ */
+ public function maintenanceRoutes(): Collection
+ {
+ return $this->maintenanceDomains()
+ ->map(function (array $domain): ?array {
+ try {
+ $url = Url::fromString(trim($domain['url']));
+ } catch (\Throwable) {
+ return null;
+ }
+ // Host and scheme stay as the proxy labels use them, so the Caddy site address is the same.
+ $scheme = $url->getScheme();
+ $host = $url->getHost();
+ $path = $url->getPath() ?: '/';
+
+ if (! in_array($scheme, ['http', 'https'], true)
+ || ! preg_match('/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/i', $host)
+ || ! preg_match('#^/[A-Za-z0-9/._~%-]*$#', $path)) {
+ return null;
+ }
+
+ return ['scheme' => $scheme, 'host' => $host, 'path' => $path, 'force_https' => $domain['force_https']];
+ })
+ ->filter()
+ ->unique(fn (array $route) => "{$route['scheme']}://{$route['host']}{$route['path']}")
+ ->values();
+ }
+
+ /**
+ * The custom maintenance page HTML, or the Coolify default page.
+ */
+ public function maintenancePageHtml(): string
+ {
+ return filled($this->maintenance_page) ? $this->maintenance_page : view('proxy.maintenance-page')->render();
+ }
+
+ public function maintenancePageFile(): string
+ {
+ return "maintenance-{$this->uuid}.html";
+ }
+
+ /**
+ * Applies the maintenance state of this resource on every server that runs it.
+ */
+ public function syncMaintenancePage(?Collection $servers = null): void
+ {
+ foreach ($servers ?? $this->maintenanceServers() as $server) {
+ if ($server->isFunctional()) {
+ $server->setupMaintenancePages();
+ }
+ }
+ }
+}
diff --git a/bootstrap/helpers/docker.php b/bootstrap/helpers/docker.php
index f502c2415c..9976efa35d 100644
--- a/bootstrap/helpers/docker.php
+++ b/bootstrap/helpers/docker.php
@@ -766,6 +766,19 @@ function isNoindexDomain(string $domain, ?Collection $noindex_domains): bool
->contains(ValidationPatterns::normalizeApplicationDomainUrl($domain));
}
+/**
+ * Caddy site address of a domain. Maintenance blocks in the base Caddyfile must use the same
+ * address as the labels, so caddy-docker-proxy merges them into one site block.
+ */
+function caddySiteAddress(string $scheme, string $host, bool $isForceHttpsEnabled): string
+{
+ if ($scheme === 'https' && ! $isForceHttpsEnabled) {
+ return "http://{$host}, https://{$host}";
+ }
+
+ return "{$scheme}://{$host}";
+}
+
function fqdnLabelsForCaddy(string $network, string $uuid, Collection $domains, bool $is_force_https_enabled = false, $onlyPort = null, ?Collection $serviceLabels = null, ?bool $is_gzip_enabled = true, ?bool $is_stripprefix_enabled = true, ?string $service_name = null, ?string $image = null, string $redirect_direction = 'both', ?string $predefinedPort = null, bool $is_http_basic_auth_enabled = false, ?string $http_basic_auth_username = null, ?string $http_basic_auth_password = null, ?Collection $noindex_domains = null, bool $is_traffic_analytics_enabled = false, array $domainPortOverrides = [], bool $supports_log_append = false, bool $supports_basic_auth_directive = false, ?int $http_basic_auth_bcrypt_cost = null, array $http_basic_auth_argon2id_options = [])
{
$labels = collect([]);
@@ -790,10 +803,7 @@ function fqdnLabelsForCaddy(string $network, string $uuid, Collection $domains,
$path = $url->getPath();
$host_without_www = str($host)->replace('www.', '');
$schema = $url->getScheme();
- $siteAddress = "{$schema}://{$host}";
- if ($schema === 'https' && ! $is_force_https_enabled) {
- $siteAddress = "http://{$host}, https://{$host}";
- }
+ $siteAddress = caddySiteAddress($schema, $host, $is_force_https_enabled);
$portlessDomain = ServiceApplication::withoutPort($domain);
$port = $url->getPort() ?? ($domainPortOverrides[$portlessDomain] ?? null);
$handle = 'handle_path';
diff --git a/bootstrap/helpers/proxy.php b/bootstrap/helpers/proxy.php
index a4b98ca5fc..613f925102 100644
--- a/bootstrap/helpers/proxy.php
+++ b/bootstrap/helpers/proxy.php
@@ -950,3 +950,16 @@ function getTraefikVersionFromDockerCompose(Server $server): ?string
return null;
}
}
+
+/**
+ * Validation rule for an HTML page that Coolify sends to the proxy in one shell command
+ * (see Server::PROXY_ERROR_PAGE_MAX_BYTES).
+ */
+function proxyPageSizeRule(string $name): Closure
+{
+ return function (string $attribute, mixed $value, Closure $fail) use ($name): void {
+ if (strlen((string) $value) > Server::PROXY_ERROR_PAGE_MAX_BYTES) {
+ $fail("The {$name} must not be larger than ".(Server::PROXY_ERROR_PAGE_MAX_BYTES / 1024).' KB.');
+ }
+ };
+}
diff --git a/database/migrations/2026_10_01_132654_add_proxy_error_page_to_servers_table.php b/database/migrations/2026_10_01_132654_add_proxy_error_page_to_servers_table.php
new file mode 100644
index 0000000000..ad1a318250
--- /dev/null
+++ b/database/migrations/2026_10_01_132654_add_proxy_error_page_to_servers_table.php
@@ -0,0 +1,25 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+return new class extends Migration
+{
+ /**
+ * Custom HTML that the proxy shows (with status 503) for requests that no resource handles.
+ */
+ public function up(): void
+ {
+ Schema::table('servers', function (Blueprint $table) {
+ $table->text('proxy_error_page')->nullable();
+ });
+ }
+
+ public function down(): void
+ {
+ Schema::table('servers', function (Blueprint $table) {
+ $table->dropColumn('proxy_error_page');
+ });
+ }
+};
diff --git a/database/migrations/2026_10_01_161644_add_maintenance_mode_to_applications_and_services_tables.php b/database/migrations/2026_10_01_161644_add_maintenance_mode_to_applications_and_services_tables.php
new file mode 100644
index 0000000000..cdafafc9e3
--- /dev/null
+++ b/database/migrations/2026_10_01_161644_add_maintenance_mode_to_applications_and_services_tables.php
@@ -0,0 +1,30 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+return new class extends Migration
+{
+ /**
+ * Maintenance mode: the proxy shows a maintenance page (status 503) instead of the resource.
+ */
+ public function up(): void
+ {
+ foreach (['applications', 'services'] as $table) {
+ Schema::table($table, function (Blueprint $table) {
+ $table->boolean('is_maintenance_enabled')->default(false);
+ $table->text('maintenance_page')->nullable();
+ });
+ }
+ }
+
+ public function down(): void
+ {
+ foreach (['applications', 'services'] as $table) {
+ Schema::table($table, function (Blueprint $table) {
+ $table->dropColumn(['is_maintenance_enabled', 'maintenance_page']);
+ });
+ }
+ }
+};
diff --git a/resources/views/livewire/project/application/configuration.blade.php b/resources/views/livewire/project/application/configuration.blade.php
index 11d6400bf6..168b102e0c 100644
--- a/resources/views/livewire/project/application/configuration.blade.php
+++ b/resources/views/livewire/project/application/configuration.blade.php
@@ -14,6 +14,7 @@
<livewire:project.application.general :application="$application" />
@elseif ($currentRoute === 'project.application.domains')
<livewire:project.application.domains :application="$application" />
+ <livewire:project.shared.maintenance :resource="$application" />
@elseif ($currentRoute === 'project.application.swarm' && $application->destination->server->isSwarm())
<livewire:project.application.swarm :application="$application" />
@elseif ($currentRoute === 'project.application.advanced')
diff --git a/resources/views/livewire/project/service/configuration.blade.php b/resources/views/livewire/project/service/configuration.blade.php
index 51dd41a9f7..3f66508f43 100644
--- a/resources/views/livewire/project/service/configuration.blade.php
+++ b/resources/views/livewire/project/service/configuration.blade.php
@@ -196,6 +196,7 @@
:lazy="(bool) ($service->server ?? $service->destination?->server)?->isTrafficAnalyticsEnabled()" />
@elseif ($currentRoute === 'project.service.domains')
<livewire:project.service.domains :service="$service" />
+ <livewire:project.shared.maintenance :resource="$service" />
@elseif ($currentRoute === 'project.service.environment-variables')
<livewire:project.shared.environment-variable.all :resource="$service" />
<livewire:project.shared.secret-manager-links :resource="$service" />
diff --git a/resources/views/livewire/project/shared/maintenance.blade.php b/resources/views/livewire/project/shared/maintenance.blade.php
new file mode 100644
index 0000000000..822d672f47
--- /dev/null
+++ b/resources/views/livewire/project/shared/maintenance.blade.php
@@ -0,0 +1,30 @@
+<form wire:submit="submit">
+ <x-unsaved-bar action="submit" targets="maintenancePage" />
+ <x-application.settings-section id="maintenance-section" title="Maintenance mode"
+ helper="Show a maintenance page with a 503 status on all domains of this resource. The containers keep running, and the change applies without a redeploy.">
+ @if ($this->isSupported)
+ <div class="flex flex-col gap-4">
+ <div class="grid gap-4 lg:grid-cols-2">
+ <x-forms.listbox canGate="update" :canResource="$resource" id="isMaintenanceEnabled"
+ label="Maintenance mode" onChange="instantSaveMaintenance" :options="[
+ ['value' => false, 'label' => 'Off: serve the resource'],
+ ['value' => true, 'label' => 'On: show the maintenance page'],
+ ]" />
+ </div>
+ <x-forms.textarea canGate="update" :canResource="$resource" id="maintenancePage" rows="10" monospace
+ label="Custom maintenance page (HTML)"
+ placeholder="Leave empty to use the Coolify default maintenance page."
+ helper="One self-contained HTML file (max {{ \App\Models\Server::PROXY_ERROR_PAGE_MAX_BYTES / 1024 }} KB) with inline CSS and images." />
+ @can('update', $resource)
+ <div class="flex gap-2">
+ <x-forms.button type="button" wire:click="resetMaintenancePage">Reset to
+ default</x-forms.button>
+ </div>
+ @endcan
+ </div>
+ @else
+ <p class="text-sm text-neutral-500 dark:text-neutral-400">Maintenance mode needs a Traefik or Caddy proxy on a
+ server that is not part of a Docker Swarm.</p>
+ @endif
+ </x-application.settings-section>
+</form>
diff --git a/resources/views/livewire/server/proxy.blade.php b/resources/views/livewire/server/proxy.blade.php
index 037466932a..0be3fbd86e 100644
--- a/resources/views/livewire/server/proxy.blade.php
+++ b/resources/views/livewire/server/proxy.blade.php
@@ -69,7 +69,7 @@
['value' => true, 'label' => 'Labels for the active proxy only'],
]" />
<x-forms.listbox id="redirectEnabled" label="Unknown requests"
- helper="Override the default 503 response for unknown hosts and stopped services."
+ helper="Control the 503 response for unknown hosts and stopped services. Custom request handling shows an error page or redirects to a URL."
onChange="instantSaveRedirect" :options="[
['value' => false, 'label' => 'Return the default 503 response'],
['value' => true, 'label' => 'Use custom request handling'],
@@ -78,9 +78,23 @@
<x-forms.input canGate="update" :canResource="$server"
placeholder="https://app.coolify.io" id="redirectUrl"
label="Redirect URL"
- helper="Leave empty to keep a custom 503 response without redirecting." />
+ helper="Leave empty to return a 503 response instead of redirecting." />
@endif
</div>
+ @if ($redirectEnabled && ! $server->isSwarm())
+ <div class="mt-4 flex flex-col gap-2">
+ <x-forms.textarea canGate="update" :canResource="$server" id="customErrorPage" rows="10"
+ monospace label="Custom error page (HTML)"
+ placeholder="Leave empty to use the Coolify default error page."
+ helper="One self-contained HTML file (max {{ \App\Models\Server::PROXY_ERROR_PAGE_MAX_BYTES / 1024 }} KB) with inline CSS and images. Visitors see it with a 503 status for unknown domains and for stopped, deploying or unhealthy resources. A Redirect URL takes priority over this page." />
+ @can('update', $server)
+ <div class="flex gap-2">
+ <x-forms.button type="button" wire:click="resetCustomErrorPage">Reset to
+ default</x-forms.button>
+ </div>
+ @endcan
+ </div>
+ @endif
</x-application.settings-section>
@php
diff --git a/resources/views/proxy/error-page.blade.php b/resources/views/proxy/error-page.blade.php
new file mode 100644
index 0000000000..4a8d2e7cc1
--- /dev/null
+++ b/resources/views/proxy/error-page.blade.php
@@ -0,0 +1,18 @@
+@extends('proxy.layout')
+
+@section('title', 'Site not available')
+
+@section('content')
+ <p class="status">503 Service Unavailable</p>
+ <h1>This site is not available at the moment</h1>
+ <p><span id="host">This site</span> cannot answer your request right now. Please try again later.</p>
+ <section>
+ <h2>Are you the site owner?</h2>
+ <ul>
+ <li>The domain is not configured on a resource in Coolify, or its DNS points to another server.</li>
+ <li>The application is stopped, still deploying, or has crashed.</li>
+ <li>The application health check is failing.</li>
+ </ul>
+ <a href="https://coolify.io/docs/troubleshoot/applications/no-available-server" rel="noopener noreferrer">Read the troubleshooting guide</a>
+ </section>
+@endsection
diff --git a/resources/views/proxy/layout.blade.php b/resources/views/proxy/layout.blade.php
new file mode 100644
index 0000000000..077b3ce2f6
--- /dev/null
+++ b/resources/views/proxy/layout.blade.php
@@ -0,0 +1,116 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <meta name="robots" content="noindex">
+ <title>@yield('title')</title>
+ <style>
+ :root {
+ color-scheme: light dark;
+ --canvas: #fafafa;
+ --card: #ffffff;
+ --hairline: #d4d4d4;
+ --text: #171717;
+ --subtle: #737373;
+ --accent: #6b16ed;
+ }
+
+ @media (prefers-color-scheme: dark) {
+ :root {
+ --canvas: #0a0a0a;
+ --card: #1c1c1c;
+ --hairline: #333333;
+ --text: #f5f5f5;
+ --subtle: #a3a3a3;
+ --accent: #fcd452;
+ }
+ }
+
+ * {
+ box-sizing: border-box;
+ }
+
+ body {
+ margin: 0;
+ min-height: 100vh;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 24px;
+ background: var(--canvas);
+ color: var(--text);
+ font: 14px/1.6 'Geist Sans', Inter, ui-sans-serif, system-ui, -apple-system, 'Segoe UI', sans-serif;
+ -webkit-font-smoothing: antialiased;
+ }
+
+ main {
+ width: 100%;
+ max-width: 560px;
+ padding: 32px;
+ background: var(--card);
+ border-radius: 12px;
+ box-shadow: 0 0 0 1px var(--hairline), 0 1px 2px rgb(0 0 0 / 0.05);
+ }
+
+ .status {
+ margin: 0 0 8px;
+ color: var(--subtle);
+ font: 12px/1.4 'Geist Mono', ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
+ }
+
+ h1 {
+ margin: 0 0 8px;
+ font-size: 20px;
+ line-height: 1.3;
+ font-weight: 600;
+ }
+
+ h2 {
+ margin: 0 0 8px;
+ font-size: 14px;
+ font-weight: 600;
+ }
+
+ p {
+ margin: 0;
+ color: var(--subtle);
+ }
+
+ section {
+ margin-top: 24px;
+ padding-top: 24px;
+ border-top: 1px solid var(--hairline);
+ }
+
+ ul {
+ margin: 0 0 16px;
+ padding-left: 20px;
+ color: var(--subtle);
+ }
+
+ li + li {
+ margin-top: 4px;
+ }
+
+ a {
+ color: var(--accent);
+ font-weight: 500;
+ }
+
+ #host {
+ color: var(--text);
+ font-weight: 500;
+ word-break: break-all;
+ }
+ </style>
+</head>
+<body>
+ <main>
+ @yield('content')
+ </main>
+ <script>
+ document.getElementById('host').textContent = location.hostname || 'This site';
+ </script>
+</body>
+</html>
diff --git a/resources/views/proxy/maintenance-page.blade.php b/resources/views/proxy/maintenance-page.blade.php
new file mode 100644
index 0000000000..236e6c8706
--- /dev/null
+++ b/resources/views/proxy/maintenance-page.blade.php
@@ -0,0 +1,9 @@
+@extends('proxy.layout')
+
+@section('title', 'Under maintenance')
+
+@section('content')
+ <p class="status">503 Service Unavailable</p>
+ <h1>We are doing some maintenance</h1>
+ <p><span id="host">This site</span> is temporarily unavailable for maintenance. Please check back soon.</p>
+@endsection
diff --git a/tests/Feature/Proxy/MaintenanceModeTest.php b/tests/Feature/Proxy/MaintenanceModeTest.php
new file mode 100644
index 0000000000..44d8ba6d6e
--- /dev/null
+++ b/tests/Feature/Proxy/MaintenanceModeTest.php
@@ -0,0 +1,289 @@
+<?php
+
+use App\Enums\ProxyTypes;
+use App\Events\ProxyStatusChanged;
+use App\Events\ProxyStatusChangedUI;
+use App\Livewire\Project\Shared\Maintenance;
+use App\Models\Application;
+use App\Models\Environment;
+use App\Models\InstanceSettings;
+use App\Models\PrivateKey;
+use App\Models\Project;
+use App\Models\Server;
+use App\Models\Service;
+use App\Models\ServiceApplication;
+use App\Models\StandaloneDocker;
+use App\Models\Team;
+use App\Models\User;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Support\Facades\Event;
+use Illuminate\Support\Facades\Process;
+use Livewire\Livewire;
+use Symfony\Component\Yaml\Yaml;
+
+uses(RefreshDatabase::class);
+
+// Servers stay in a static identity map; do not leak them into later test files.
+afterEach(fn () => Server::flushIdentityMap());
+
+beforeEach(function () {
+ Server::flushIdentityMap();
+ Event::fake([ProxyStatusChanged::class, ProxyStatusChangedUI::class]);
+ InstanceSettings::forceCreate(['id' => 0]);
+ config(['constants.ssh.mux_enabled' => false]);
+ fakeProxyFileUploads();
+
+ $this->team = Team::factory()->create();
+ $this->server = Server::factory()->create([
+ 'team_id' => $this->team->id,
+ 'user' => 'cooluser',
+ 'private_key_id' => PrivateKey::factory()->create(['team_id' => $this->team->id])->id,
+ ]);
+ $this->server->settings->update(['is_reachable' => true, 'is_usable' => true, 'force_disabled' => false]);
+ $this->server->proxy->type = ProxyTypes::TRAEFIK->value;
+ $this->server->save();
+
+ $this->destination = StandaloneDocker::where('server_id', $this->server->id)->first()
+ ?? StandaloneDocker::factory()->create(['server_id' => $this->server->id]);
+ $project = Project::factory()->create(['team_id' => $this->team->id]);
+ $this->environment = Environment::factory()->create(['project_id' => $project->id]);
+});
+
+function maintenanceApplication(array $attributes = []): Application
+{
+ $test = test();
+
+ return Application::factory()->create(array_merge([
+ 'environment_id' => $test->environment->id,
+ 'destination_id' => $test->destination->id,
+ 'destination_type' => $test->destination->getMorphClass(),
+ 'fqdn' => 'https://app.example.com',
+ ], $attributes));
+}
+
+function maintenanceService(array $domains): Service
+{
+ $test = test();
+ $service = Service::factory()->create([
+ 'environment_id' => $test->environment->id,
+ 'server_id' => $test->server->id,
+ 'destination_id' => $test->destination->id,
+ 'destination_type' => $test->destination->getMorphClass(),
+ ]);
+ foreach ($domains as $name => $fqdn) {
+ ServiceApplication::create(['name' => $name, 'service_id' => $service->id, 'image' => 'nginx', 'fqdn' => $fqdn]);
+ }
+
+ return $service;
+}
+
+function maintenanceServer(): Server
+{
+ return Server::find(test()->server->id);
+}
+
+/**
+ * @return array<int, string>
+ */
+function maintenanceScriptLines(): array
+{
+ $lines = [];
+ Process::assertRan(function ($process) use (&$lines) {
+ array_push($lines, ...explode("\n", $process->command));
+
+ return true;
+ });
+
+ return $lines;
+}
+
+it('routes the maintenance domains through Traefik with a priority just above the resource router', function () {
+ $application = maintenanceApplication(['fqdn' => 'https://app.example.com,http://app.example.com/api', 'is_maintenance_enabled' => true]);
+
+ $config = Yaml::parse(maintenanceServer()->maintenanceTraefikConfiguration(collect([$application])));
+ $routers = $config['http']['routers'];
+ $rootRule = 'Host(`app.example.com`) && PathPrefix(`/`)';
+ $apiRule = 'Host(`app.example.com`) && PathPrefix(`/api`)';
+
+ expect($routers["coolify-maintenance-{$application->uuid}-0-http"])->toMatchArray([
+ 'entryPoints' => ['http'],
+ 'rule' => $rootRule,
+ 'service' => 'coolify-maintenance-noop',
+ 'middlewares' => ['coolify-maintenance-headers', "coolify-maintenance-{$application->uuid}"],
+ 'priority' => strlen($rootRule) + 1,
+ ])
+ ->and($routers["coolify-maintenance-{$application->uuid}-0-https"]['tls'])->toBe(['certResolver' => 'letsencrypt'])
+ // http:// domains get no TLS router.
+ ->and($routers)->not->toHaveKey("coolify-maintenance-{$application->uuid}-1-https")
+ ->and($routers["coolify-maintenance-{$application->uuid}-1-http"]['priority'])->toBe(strlen($apiRule) + 1)
+ // A resource router on a longer path of the same host keeps a higher priority.
+ ->and(strlen($apiRule))->toBeGreaterThan($routers["coolify-maintenance-{$application->uuid}-0-http"]['priority'])
+ ->and($config['http']['middlewares']["coolify-maintenance-{$application->uuid}"]['errors'])->toBe([
+ 'status' => ['503'],
+ 'service' => 'coolify-maintenance-pages',
+ 'query' => "/maintenance-{$application->uuid}.html",
+ ])
+ ->and($config['http']['middlewares']['coolify-maintenance-headers']['headers']['customResponseHeaders'])->toBe(['Retry-After' => '300'])
+ ->and($config['http']['services']['coolify-maintenance-noop']['loadBalancer']['servers'])->toBe([])
+ ->and($config['http']['services']['coolify-maintenance-pages']['loadBalancer']['servers'])->toBe([['url' => 'http://coolify-proxy-error-pages:80']]);
+});
+
+it('writes Caddy maintenance blocks with the same site address as the resource labels', function (bool $forceHttps, string $domain) {
+ $application = maintenanceApplication(['fqdn' => $domain, 'is_maintenance_enabled' => true]);
+ $application->settings->update(['is_force_https_enabled' => $forceHttps]);
+ $application->refresh();
+ $labelAddress = str(fqdnLabelsForCaddy('coolify', $application->uuid, collect([$domain]), $forceHttps)->first(fn ($label) => str_starts_with($label, 'caddy_0=')))->after('caddy_0=')->value();
+ $matcher = "@coolify-maintenance-{$application->uuid}-0";
+ $path = parse_url($domain, PHP_URL_PATH) ?: '/';
+
+ $caddyfile = maintenanceServer()->caddyBaseCaddyfile(collect([$application]));
+
+ expect($caddyfile)
+ ->toStartWith("import /dynamic/*.caddy\n")
+ ->toContain("\n\n{$labelAddress} {\n\t{$matcher} path {$path}*\n\thandle {$matcher} {")
+ ->toContain("rewrite /maintenance-{$application->uuid}.html")
+ ->toContain('copy_response 503');
+})->with([
+ 'https' => [false, 'https://app.example.com'],
+ 'forced https' => [true, 'https://app.example.com'],
+ 'http with path' => [false, 'http://app.example.com/api'],
+]);
+
+it('keeps the base Caddyfile to the import line without maintenance resources', function () {
+ expect(maintenanceServer()->caddyBaseCaddyfile(collect()))->toBe("import /dynamic/*.caddy\n");
+});
+
+it('skips domains that could inject proxy configuration', function () {
+ $application = maintenanceApplication(['fqdn' => 'https://ok.example.com,https://bad.example.com/a b,https://bad.example.com/{x},https://evil.example.com`)', 'is_maintenance_enabled' => true]);
+
+ expect($application->maintenanceRoutes()->pluck('host')->all())->toBe(['ok.example.com']);
+});
+
+it('collects the domains of Docker Compose applications and services', function () {
+ $compose = maintenanceApplication([
+ 'build_pack' => 'dockercompose',
+ 'fqdn' => null,
+ 'docker_compose_domains' => json_encode(['web' => ['domain' => 'https://web.example.com,https://www.example.com'], 'api' => ['domain' => 'https://web.example.com/api'], 'db' => ['domain' => '']]),
+ ]);
+ $service = maintenanceService(['ghost' => 'https://blog.example.com', 'admin' => 'https://admin.example.com/ghost']);
+
+ expect($compose->maintenanceRoutes()->map(fn ($route) => $route['host'].$route['path'])->all())->toBe(['web.example.com/', 'www.example.com/', 'web.example.com/api'])
+ ->and($service->maintenanceRoutes()->map(fn ($route) => $route['host'].$route['path'])->all())->toBe(['blog.example.com/', 'admin.example.com/ghost']);
+});
+
+it('writes the pages and the Traefik routes through sudo, and removes them when maintenance ends', function () {
+ $application = maintenanceApplication(['is_maintenance_enabled' => true]);
+ $service = maintenanceService(['ghost' => 'https://blog.example.com']);
+ $service->forceFill(['is_maintenance_enabled' => true])->save();
+ $pages = '/data/coolify/proxy/error-pages';
+
+ maintenanceServer()->setupMaintenancePages();
+ $lines = maintenanceScriptLines();
+
+ expect($lines)->toContain("sudo find $pages -maxdepth 1 -name 'maintenance-*.html' ! -name 'maintenance-{$application->uuid}.html' ! -name 'maintenance-{$service->uuid}.html' -delete")
+ ->and(collect($lines)->contains(fn ($line) => str_starts_with($line, 'sudo docker start coolify-proxy-error-pages')))->toBeTrue()
+ ->and(writtenProxyFile($lines, "$pages/maintenance-{$application->uuid}.html"))->toContain('We are doing some maintenance')
+ ->and(writtenProxyFile($lines, "$pages/maintenance-{$service->uuid}.html"))->toContain('We are doing some maintenance')
+ ->and(writtenProxyFile($lines, '/data/coolify/proxy//dynamic/coolify-maintenance.yaml'))
+ ->toContain('app.example.com')->toContain('blog.example.com');
+
+ $application->forceFill(['is_maintenance_enabled' => false])->save();
+ $service->forceFill(['is_maintenance_enabled' => false])->save();
+ maintenanceServer()->setupMaintenancePages();
+
+ expect(maintenanceScriptLines())->toContain('sudo rm -f /data/coolify/proxy//dynamic/coolify-maintenance.yaml')
+ ->toContain("sudo find $pages -maxdepth 1 -name 'maintenance-*.html' -delete");
+});
+
+it('writes the maintenance blocks into the base Caddyfile on Caddy servers', function () {
+ $this->server->proxy->type = ProxyTypes::CADDY->value;
+ $this->server->save();
+ $application = maintenanceApplication(['is_maintenance_enabled' => true]);
+
+ maintenanceServer()->setupMaintenancePages();
+
+ expect(writtenProxyFile(maintenanceScriptLines(), '/data/coolify/proxy/caddy/dynamic/Caddyfile'))
+ ->toContain("@coolify-maintenance-{$application->uuid}-0 path /*");
+});
+
+it('keeps the page container for maintenance when a redirect URL replaces the catch-all page', function () {
+ maintenanceApplication(['is_maintenance_enabled' => true]);
+ $server = maintenanceServer();
+ $server->proxy->redirect_url = 'https://example.com';
+ $server->save();
+
+ $server->setupProxyErrorPageContainer();
+
+ expect(collect(maintenanceScriptLines())->contains(fn ($line) => str_contains($line, 'docker run -d --name coolify-proxy-error-pages')))->toBeTrue();
+});
+
+it('does not touch Swarm servers', function () {
+ maintenanceApplication(['is_maintenance_enabled' => true]);
+ $this->server->settings->update(['is_swarm_manager' => true]);
+
+ $server = maintenanceServer();
+ $server->setupMaintenancePages();
+
+ expect($server->maintenanceResources())->toBeEmpty();
+ Process::assertNothingRan();
+});
+
+function maintenanceUser(Team $team, string $role): User
+{
+ $user = User::factory()->create();
+ $user->teams()->attach($team, ['role' => $role]);
+
+ return $user;
+}
+
+it('lets an admin enable maintenance and save a custom page', function () {
+ $application = maintenanceApplication();
+ $this->actingAs(maintenanceUser($this->team, 'admin'));
+ session(['currentTeam' => $this->team]);
+
+ Livewire::test(Maintenance::class, ['resource' => $application])
+ ->set('maintenancePage', '<h1>Back soon</h1>')
+ ->call('submit')
+ ->assertDispatched('success')
+ ->set('isMaintenanceEnabled', true)
+ ->call('instantSaveMaintenance')
+ ->assertDispatched('success');
+
+ $application->refresh();
+ expect($application->is_maintenance_enabled)->toBeTrue()
+ ->and($application->maintenance_page)->toBe('<h1>Back soon</h1>')
+ ->and(writtenProxyFile(maintenanceScriptLines(), "/data/coolify/proxy/error-pages/maintenance-{$application->uuid}.html"))->toBe('<h1>Back soon</h1>');
+});
+
+it('rejects a maintenance page larger than the limit', function () {
+ $application = maintenanceApplication();
+ $this->actingAs(maintenanceUser($this->team, 'owner'));
+ session(['currentTeam' => $this->team]);
+
+ Livewire::test(Maintenance::class, ['resource' => $application])
+ ->set('maintenancePage', str_repeat('a', Server::PROXY_ERROR_PAGE_MAX_BYTES + 1))
+ ->call('submit')
+ ->assertDispatched('error');
+
+ expect($application->fresh()->maintenance_page)->toBeNull();
+});
+
+it('does not let a member or another team change maintenance mode', function (string $who) {
+ $service = maintenanceService(['ghost' => 'https://blog.example.com']);
+ $team = $who === 'member' ? $this->team : Team::factory()->create();
+ $this->actingAs(maintenanceUser($team, $who === 'member' ? 'member' : 'owner'));
+ session(['currentTeam' => $team]);
+
+ Livewire::test(Maintenance::class, ['resource' => $service])
+ ->set('isMaintenanceEnabled', true)
+ ->call('instantSaveMaintenance')
+ ->assertDispatched('error')
+ ->set('maintenancePage', '<h1>Hacked</h1>')
+ ->call('submit')
+ ->assertDispatched('error');
+
+ $service->refresh();
+ expect($service->is_maintenance_enabled)->toBeFalse()
+ ->and($service->maintenance_page)->toBeNull();
+ Process::assertNothingRan();
+})->with(['member', 'other team']);
diff --git a/tests/Feature/Proxy/NonRootProxyCommandsTest.php b/tests/Feature/Proxy/NonRootProxyCommandsTest.php
index f1cda7eb28..ea0c0d19e8 100644
--- a/tests/Feature/Proxy/NonRootProxyCommandsTest.php
+++ b/tests/Feature/Proxy/NonRootProxyCommandsTest.php
@@ -93,8 +93,10 @@ it('writes the Caddyfile through sudo', function () {
StartProxy::run($this->server, async: false, force: true);
+ $base64 = base64_encode("import /dynamic/*.caddy\n");
+
expect(nonRootProxyScriptLines())
- ->toContain("echo 'import /dynamic/*.caddy' | sudo tee /data/coolify/proxy/caddy/dynamic/Caddyfile > /dev/null");
+ ->toContain("echo '{$base64}' | sudo base64 -d | sudo tee /data/coolify/proxy/caddy/dynamic/Caddyfile > /dev/null");
});
it('deploys the swarm proxy stack with an absolute compose file path', function () {
diff --git a/tests/Feature/Proxy/ProxyErrorPageTest.php b/tests/Feature/Proxy/ProxyErrorPageTest.php
new file mode 100644
index 0000000000..4d1f939459
--- /dev/null
+++ b/tests/Feature/Proxy/ProxyErrorPageTest.php
@@ -0,0 +1,286 @@
+<?php
+
+use App\Actions\Proxy\StopProxy;
+use App\Enums\ProxyTypes;
+use App\Events\ProxyStatusChanged;
+use App\Events\ProxyStatusChangedUI;
+use App\Models\InstanceSettings;
+use App\Models\PrivateKey;
+use App\Models\Server;
+use App\Models\Team;
+use App\Models\User;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Support\Facades\Event;
+use Illuminate\Support\Facades\Process;
+use Livewire\Livewire;
+use Symfony\Component\Yaml\Yaml;
+
+uses(RefreshDatabase::class);
+
+// Servers stay in a static identity map; do not leak them into later test files.
+afterEach(fn () => Server::flushIdentityMap());
+
+beforeEach(function () {
+ Server::flushIdentityMap();
+ Event::fake([ProxyStatusChanged::class, ProxyStatusChangedUI::class]);
+ InstanceSettings::forceCreate(['id' => 0]);
+ config(['constants.ssh.mux_enabled' => false]);
+ fakeProxyFileUploads();
+
+ $this->team = Team::factory()->create();
+ $this->server = Server::factory()->create([
+ 'team_id' => $this->team->id,
+ 'user' => 'cooluser',
+ 'private_key_id' => PrivateKey::factory()->create(['team_id' => $this->team->id])->id,
+ ]);
+ $this->server->settings->update(['is_reachable' => true, 'is_usable' => true, 'force_disabled' => false]);
+});
+
+function useErrorPageProxy(Server $server, string $proxyType, array $proxy = []): Server
+{
+ $server->proxy->type = $proxyType;
+ foreach ($proxy as $key => $value) {
+ $server->proxy->{$key} = $value;
+ }
+ $server->save();
+
+ return $server->refresh();
+}
+
+/**
+ * @return array<int, string>
+ */
+function errorPageScriptLines(): array
+{
+ $lines = [];
+ Process::assertRan(function ($process) use (&$lines) {
+ array_push($lines, ...explode("\n", $process->command));
+
+ return true;
+ });
+
+ return $lines;
+}
+
+it('routes the Traefik catch-all through the errors middleware and keeps the 503', function () {
+ $server = useErrorPageProxy($this->server, ProxyTypes::TRAEFIK->value);
+
+ $config = Yaml::parse($server->defaultRedirectConfiguration());
+
+ expect($config['http']['routers']['catchall']['service'])->toBe('noop')
+ ->and($config['http']['routers']['catchall']['middlewares'])->toBe(['error-pages'])
+ ->and($config['http']['services']['noop']['loadBalancer']['servers'])->toBe([])
+ ->and($config['http']['middlewares']['error-pages']['errors'])->toBe([
+ 'status' => ['503'],
+ 'service' => 'error-pages',
+ 'query' => '/503.html',
+ ])
+ ->and($config['http']['services']['error-pages']['loadBalancer']['servers'])
+ ->toBe([['url' => 'http://coolify-proxy-error-pages:80']]);
+});
+
+it('catches plain HTTP with a router without TLS', function (array $proxy, array $middlewares) {
+ $server = useErrorPageProxy($this->server, ProxyTypes::TRAEFIK->value, $proxy);
+
+ $routers = Yaml::parse($server->defaultRedirectConfiguration())['http']['routers'];
+
+ // A router with `tls` matches only HTTPS, so plain HTTP needs the catchall-http router.
+ expect($routers['catchall']['entryPoints'])->toBe(['https'])
+ ->and($routers['catchall']['tls'])->toBe(['certResolver' => 'letsencrypt'])
+ ->and($routers['catchall-http'])->toBe([
+ 'entryPoints' => ['http'],
+ 'service' => 'noop',
+ 'rule' => 'PathPrefix(`/`)',
+ 'priority' => -1000,
+ 'middlewares' => $middlewares,
+ ]);
+})->with([
+ 'error page' => [[], ['error-pages']],
+ 'redirect URL' => [['redirect_url' => 'https://example.com'], ['redirect-regexp']],
+]);
+
+it('serves the error page through Caddy with a 503 status', function () {
+ $server = useErrorPageProxy($this->server, ProxyTypes::CADDY->value);
+
+ expect($server->defaultRedirectConfiguration())
+ ->toContain('reverse_proxy coolify-proxy-error-pages:80 {')
+ ->toContain('rewrite /503.html')
+ ->toContain('copy_response 503')
+ ->not->toContain('respond 503');
+});
+
+it('keeps the redirect URL ahead of the error page', function (string $proxyType) {
+ $server = useErrorPageProxy($this->server, $proxyType, ['redirect_url' => 'https://example.com']);
+ $server->proxy_error_page = '<h1>custom</h1>';
+ $server->save();
+
+ $configuration = $server->defaultRedirectConfiguration();
+ $server->setupDefaultRedirect();
+ $lines = errorPageScriptLines();
+
+ expect($configuration)->toContain('https://example.com')->not->toContain('error-pages')
+ ->and($lines)->toContain('sudo docker rm -f coolify-proxy-error-pages >/dev/null 2>&1 || sudo true')
+ ->and(implode("\n", $lines))->not->toContain('docker run');
+})->with([ProxyTypes::TRAEFIK->value, ProxyTypes::CADDY->value]);
+
+it('removes the catch-all and the page container when the default redirect is disabled', function () {
+ $server = useErrorPageProxy($this->server, ProxyTypes::TRAEFIK->value, ['redirect_enabled' => false]);
+
+ $server->setupDefaultRedirect();
+ $lines = errorPageScriptLines();
+
+ expect($lines)
+ ->toContain('sudo rm -f /data/coolify/proxy//dynamic/default_redirect_503.yaml')
+ ->toContain('sudo docker rm -f coolify-proxy-error-pages >/dev/null 2>&1 || sudo true')
+ ->and(writtenProxyFile($lines, '/data/coolify/proxy//dynamic/default_redirect_503.yaml'))->toBeNull();
+});
+
+it('starts the page container through sudo before it writes the catch-all', function (string $proxyType, string $catchAll) {
+ $server = useErrorPageProxy($this->server, $proxyType);
+
+ $server->setupDefaultRedirect();
+ $lines = errorPageScriptLines();
+
+ $runLine = collect($lines)->search(fn (string $line) => str_contains($line, 'docker run -d --name coolify-proxy-error-pages'));
+ $catchAllLine = collect($lines)->search(fn (string $line) => str_contains($line, "tee $catchAll"));
+
+ expect($runLine)->toBeInt()
+ ->and($catchAllLine)->toBeInt()
+ ->and($runLine)->toBeLessThan($catchAllLine)
+ ->and($lines[$runLine])->toBe('sudo docker start coolify-proxy-error-pages >/dev/null 2>&1 || sudo docker run -d --name coolify-proxy-error-pages --network coolify --restart unless-stopped --label coolify.managed=true -v /data/coolify/proxy/error-pages:/www:ro busybox:musl httpd -f -p 80 -h /www')
+ ->and($lines)->toContain('sudo mkdir -p /data/coolify/proxy/error-pages && sudo find /data/coolify/proxy/error-pages -user root -exec chown -h cooluser:cooluser {} + && sudo chmod o-rwx /data/coolify/proxy/error-pages')
+ // The page goes through scp, then sudo moves it into place.
+ ->and(collect($lines)->contains(fn (string $line) => preg_match('#^sudo mv -f /tmp/coolify-upload-[0-9a-f]+ /data/coolify/proxy/error-pages/503.html$#', $line) === 1))->toBeTrue()
+ ->and($lines)->toContain('sudo chmod 644 /data/coolify/proxy/error-pages/503.html')
+ ->and(writtenProxyFile($lines, '/data/coolify/proxy/error-pages/503.html'))->toContain('This site is not available at the moment')
+ ->and(writtenProxyFile($lines, $catchAll))->toContain('coolify-proxy-error-pages');
+})->with([
+ 'traefik' => [ProxyTypes::TRAEFIK->value, '/data/coolify/proxy//dynamic/default_redirect_503.yaml'],
+ 'caddy' => [ProxyTypes::CADDY->value, '/data/coolify/proxy/caddy/dynamic/default_redirect_503.caddy'],
+]);
+
+it('pushes the custom page and falls back to the default page after a reset', function () {
+ $server = useErrorPageProxy($this->server, ProxyTypes::TRAEFIK->value);
+ $server->proxy_error_page = '<h1>Maintenance</h1>';
+ $server->save();
+
+ $server->setupDefaultRedirect();
+ expect(writtenProxyFile(errorPageScriptLines(), '/data/coolify/proxy/error-pages/503.html'))->toBe('<h1>Maintenance</h1>');
+
+ $server->proxy_error_page = null;
+ $server->save();
+ $server->setupDefaultRedirect();
+
+ expect(writtenProxyFile(errorPageScriptLines(), '/data/coolify/proxy/error-pages/503.html'))
+ ->toContain('This site is not available at the moment')
+ ->toContain('https://coolify.io/docs/troubleshoot/applications/no-available-server')
+ ->not->toContain($server->name)
+ ->not->toContain($server->ip)
+ ->not->toContain($this->team->name);
+});
+
+it('keeps Swarm servers on the plain catch-all without a page container', function (string $swarmSetting) {
+ $server = useErrorPageProxy($this->server, ProxyTypes::TRAEFIK->value);
+ $server->settings->update([$swarmSetting => true]);
+ $server->refresh();
+
+ $config = Yaml::parse($server->defaultRedirectConfiguration());
+ $server->setupDefaultRedirect();
+
+ expect($config['http']['routers'])->toBe(['catchall' => [
+ 'entryPoints' => ['http', 'https'],
+ 'service' => 'noop',
+ 'rule' => 'PathPrefix(`/`)',
+ 'tls' => ['certResolver' => 'letsencrypt'],
+ 'priority' => -1000,
+ ]])
+ ->and($config['http'])->not->toHaveKey('middlewares')
+ ->and(array_keys($config['http']['services']))->toBe(['noop'])
+ ->and(implode("\n", errorPageScriptLines()))->not->toContain('coolify-proxy-error-pages');
+})->with(['is_swarm_manager', 'is_swarm_worker']);
+
+it('removes the page container when the proxy stops', function () {
+ $server = useErrorPageProxy($this->server, ProxyTypes::TRAEFIK->value);
+
+ StopProxy::run($server);
+
+ expect(errorPageScriptLines())->toContain('sudo docker rm -f coolify-proxy-error-pages 2>/dev/null || sudo true');
+});
+
+function errorPageUser(Team $team, string $role): User
+{
+ $user = User::factory()->create();
+ $user->teams()->attach($team, ['role' => $role]);
+
+ return $user;
+}
+
+it('lets an admin save and reset the custom error page', function () {
+ $server = useErrorPageProxy($this->server, ProxyTypes::TRAEFIK->value);
+ $this->actingAs(errorPageUser($this->team, 'admin'));
+ session(['currentTeam' => $this->team]);
+
+ // The page loads the proxy configuration before the global save bar submits it.
+ $component = Livewire::test('server.proxy', ['server' => $server])
+ ->set('proxySettings', "services:\n traefik:\n image: traefik:v3.6\n ports:\n - '80:80'\n")
+ ->set('customErrorPage', '<h1>Maintenance</h1>')
+ ->call('submit')
+ ->assertDispatched('success');
+
+ expect($server->fresh()->proxy_error_page)->toBe('<h1>Maintenance</h1>')
+ ->and(writtenProxyFile(errorPageScriptLines(), '/data/coolify/proxy/error-pages/503.html'))->toBe('<h1>Maintenance</h1>');
+
+ $component->call('resetCustomErrorPage')
+ ->assertDispatched('success')
+ ->assertSet('customErrorPage', null);
+
+ expect($server->fresh()->proxy_error_page)->toBeNull();
+});
+
+it('uploads a custom page larger than one shell argument', function () {
+ $server = useErrorPageProxy($this->server, ProxyTypes::TRAEFIK->value);
+ $page = '<h1>Big</h1>'.str_repeat('a', 300 * 1024);
+ $server->proxy_error_page = $page;
+ $server->save();
+
+ $server->setupDefaultRedirect();
+ $lines = errorPageScriptLines();
+
+ // Linux limits one shell argument to 128 KiB, so the page must not be inside a command.
+ expect(writtenProxyFile($lines, '/data/coolify/proxy/error-pages/503.html'))->toBe($page)
+ ->and(collect($lines)->max(fn (string $line) => strlen($line)))->toBeLessThan(128 * 1024);
+});
+
+it('rejects a custom error page larger than the limit', function () {
+ $server = useErrorPageProxy($this->server, ProxyTypes::TRAEFIK->value);
+ $this->actingAs(errorPageUser($this->team, 'owner'));
+ session(['currentTeam' => $this->team]);
+
+ Livewire::test('server.proxy', ['server' => $server])
+ ->set('customErrorPage', str_repeat('a', Server::PROXY_ERROR_PAGE_MAX_BYTES + 1))
+ ->call('submit')
+ ->assertDispatched('error');
+
+ expect($server->fresh()->proxy_error_page)->toBeNull();
+ Process::assertNothingRan();
+});
+
+it('does not let a member or another team change the custom error page', function (string $who) {
+ $server = useErrorPageProxy($this->server, ProxyTypes::TRAEFIK->value);
+ $server->proxy_error_page = '<h1>Original</h1>';
+ $server->save();
+
+ $team = $who === 'member' ? $this->team : Team::factory()->create();
+ $this->actingAs(errorPageUser($team, $who === 'member' ? 'member' : 'owner'));
+ session(['currentTeam' => $team]);
+
+ Livewire::test('server.proxy', ['server' => $server])
+ ->set('customErrorPage', '<h1>Hacked</h1>')
+ ->call('submit')
+ ->assertDispatched('error')
+ ->call('resetCustomErrorPage')
+ ->assertDispatched('error');
+
+ expect($server->fresh()->proxy_error_page)->toBe('<h1>Original</h1>');
+ Process::assertNothingRan();
+})->with(['member', 'other team']);
diff --git a/tests/Pest.php b/tests/Pest.php
index 07cfd25a16..20645621ce 100644
--- a/tests/Pest.php
+++ b/tests/Pest.php
@@ -1,6 +1,8 @@
<?php
use App\Models\Server;
+use Illuminate\Process\PendingProcess;
+use Illuminate\Support\Facades\Process;
use Illuminate\Support\Once;
use Livewire\Features\SupportTesting\Testable;
use Tests\TestCase;
@@ -141,3 +143,39 @@ function loginAndSkipBoarding(string $email = '[email protected]', string $passwo
// {
// // ..
// }
+
+/**
+ * Fakes all processes and keeps the content of every file that Server::uploadProxyFile()
+ * copies with scp, keyed by the remote upload path.
+ */
+function fakeProxyFileUploads(): void
+{
+ $GLOBALS['proxyFileUploads'] = [];
+ Process::fake(function (PendingProcess $process) {
+ if (preg_match("#'(/[^']*coolify-proxy-file-[^']+)'.*'(/tmp/coolify-upload-[0-9a-f]+)'#", (string) $process->command, $matches)) {
+ $GLOBALS['proxyFileUploads'][$matches[2]] = file_get_contents($matches[1]);
+ }
+
+ return Process::result();
+ });
+}
+
+/**
+ * The last content written to $file on the server, with Server::uploadProxyFile() or with
+ * `echo '<base64>' | base64 -d | tee $file`.
+ *
+ * @param array<int, string> $lines remote script lines (see Process::assertRan)
+ */
+function writtenProxyFile(array $lines, string $file): ?string
+{
+ $content = null;
+ foreach ($lines as $line) {
+ if (preg_match('#mv -f (/tmp/coolify-upload-[0-9a-f]+) '.preg_quote($file, '#').'$#', $line, $matches)) {
+ $content = $GLOBALS['proxyFileUploads'][$matches[1]] ?? null;
+ } elseif (str_contains($line, "tee $file") && preg_match("/echo '([A-Za-z0-9+\/=]+)'/", $line, $matches)) {
+ $content = base64_decode($matches[1]);
+ }
+ }
+
+ return $content;
+}