Skip to content

Modern Docker Management, Designed for Everyone

feat: add Hostname configuration (#4391)

Rob Loachd34c04623f3e
diff --git a/backend/internal/container/service.go b/backend/internal/container/service.go
index 24354494b..2e0093769 100644
--- a/backend/internal/container/service.go
+++ b/backend/internal/container/service.go
@@ -851,7 +851,7 @@ func applyEditToContainerConfig(cfg container.Config, previousBindings network.P
}
return container.Config{ //exhaustruct:enforce
- Hostname: cfg.Hostname,
+ Hostname: kit.Ternary(req.Hostname != nil, strings.TrimSpace(kit.FromPtr(req.Hostname)), cfg.Hostname),
Domainname: cfg.Domainname,
User: mo.PointerToOption(req.User).OrElse(cfg.User),
AttachStdin: cfg.AttachStdin,
diff --git a/backend/internal/container/service_test.go b/backend/internal/container/service_test.go
index 3d9c90011..5a85b2d31 100644
--- a/backend/internal/container/service_test.go
+++ b/backend/internal/container/service_test.go
@@ -545,6 +545,22 @@ func TestApplyEditRecomputesExposedPorts(t *testing.T) {
require.Contains(t, hc.PortBindings, network.MustParsePort("443/tcp"))
}
+func TestApplyEditHostname(t *testing.T) {
+ // nil preserves the existing hostname
+ cfg, err := applyEditToContainerConfig(container.Config{Hostname: "old-host"}, nil, containertypes.Edit{})
+ require.NoError(t, err)
+ require.Equal(t, "old-host", cfg.Hostname)
+
+ cfg, err = applyEditToContainerConfig(cfg, nil, containertypes.Edit{Hostname: new(" new-host ")})
+ require.NoError(t, err)
+ require.Equal(t, "new-host", cfg.Hostname)
+
+ // empty clears it so Docker assigns its default on recreate
+ cfg, err = applyEditToContainerConfig(cfg, nil, containertypes.Edit{Hostname: new("")})
+ require.NoError(t, err)
+ require.Empty(t, cfg.Hostname)
+}
+
func TestBuildEditNetworkingConfig(t *testing.T) {
containerInspect := container.InspectResponse{
HostConfig: &container.HostConfig{NetworkMode: "my-net"},
diff --git a/frontend/messages/en.json b/frontend/messages/en.json
index 683cece71..9e92eda21 100644
--- a/frontend/messages/en.json
+++ b/frontend/messages/en.json
@@ -785,6 +785,7 @@
"container_user_placeholder": "1000:1000 or username",
"container_user_description": "User to run the container as",
"container_hostname_placeholder": "my-hostname",
+ "container_hostname_invalid": "Enter a valid hostname",
"container_domain_label": "Domain Name",
"container_domain_placeholder": "example.com",
"container_compose_gitops_managed_title": "GitOps Managed — Read Only",
diff --git a/frontend/src/lib/components/containers/container-form/container-form-state.ts b/frontend/src/lib/components/containers/container-form/container-form-state.ts
index 9b8a66fbd..65be86269 100644
--- a/frontend/src/lib/components/containers/container-form/container-form-state.ts
+++ b/frontend/src/lib/components/containers/container-form/container-form-state.ts
@@ -62,6 +62,18 @@ export const LINUX_CAPABILITIES = [
'WAKE_ALARM'
] as const;
+// RFC 1123 hostname: 1-63 character labels, 253 total.
+const HOSTNAME_PATTERN =
+ /^(?!\d+\.\d+\.\d+\.\d+$)(?=.{1,253}$)[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
+
+function hostnameSchema(existingHostname = '') {
+ return z
+ .string()
+ .refine((value) => !value || value === existingHostname || HOSTNAME_PATTERN.test(value), m.container_hostname_invalid())
+ .optional()
+ .default('');
+}
+
export const containerFormSchema = z.object({
name: z.string().min(1, m.container_name_required()),
image: z.string().min(1, m.image_is_required()),
@@ -69,6 +81,7 @@ export const containerFormSchema = z.object({
entrypoint: z.string().optional().default(''),
workingDir: z.string().optional().default(''),
user: z.string().optional().default(''),
+ hostname: hostnameSchema(),
restartPolicy: z.string().default('no'),
restartMaxRetries: z.coerce.number().min(0).default(0),
memoryMb: z.coerce.number().min(0).default(0),
@@ -86,6 +99,11 @@ export const containerFormSchema = z.object({
healthRetries: z.coerce.number().min(0).default(0)
});
+// Docker accepts hostnames outside RFC 1123, so an unchanged existing one must not block saving other edits.
+export function editContainerFormSchema(existingHostname = '') {
+ return containerFormSchema.extend({ hostname: hostnameSchema(existingHostname) });
+}
+
export type ContainerFormSchema = typeof containerFormSchema;
export type ContainerFormValues = z.infer<ContainerFormSchema>;
@@ -123,6 +141,7 @@ export function emptyContainerFormValues(): ContainerFormValues {
entrypoint: '',
workingDir: '',
user: '',
+ hostname: '',
restartPolicy: 'no',
restartMaxRetries: 0,
memoryMb: 0,
@@ -168,6 +187,7 @@ export function formValuesFromEditConfig(cfg: ContainerEditConfigDto): Container
entrypoint: joinShellWords(cfg.entrypoint),
workingDir: cfg.workingDir ?? '',
user: cfg.user ?? '',
+ hostname: cfg.hostname ?? '',
restartPolicy: hc.restartPolicy?.name || 'no',
restartMaxRetries: hc.restartPolicy?.maximumRetryCount ?? 0,
memoryMb: hc.memory ? Math.round(hc.memory / (1024 * 1024)) : 0,
@@ -372,6 +392,7 @@ export function toCreateRequest(values: ContainerFormValues, rows: ContainerForm
entrypoint: values.entrypoint.trim() ? splitShellWords(values.entrypoint.trim()) : undefined,
workingDir: values.workingDir.trim() || undefined,
user: values.user.trim() || undefined,
+ hostname: values.hostname.trim() || undefined,
env: env.length > 0 ? env : undefined,
labels: Object.keys(labels).length > 0 ? labels : undefined,
healthcheck: buildHealthcheck(values),
@@ -404,6 +425,7 @@ export function toEditRequest(values: ContainerFormValues, rows: ContainerFormRo
image: values.image.trim(),
workingDir: values.workingDir.trim(),
user: values.user.trim(),
+ hostname: values.hostname.trim(),
command: splitShellWords(values.command.trim()),
entrypoint: splitShellWords(values.entrypoint.trim()),
environment: buildEnv(rows),
diff --git a/frontend/src/lib/components/containers/container-form/container-form.svelte b/frontend/src/lib/components/containers/container-form/container-form.svelte
index 60921066d..ef2ff195e 100644
--- a/frontend/src/lib/components/containers/container-form/container-form.svelte
+++ b/frontend/src/lib/components/containers/container-form/container-form.svelte
@@ -34,6 +34,7 @@
submitting = false,
cancelHref = '/containers',
environmentId,
+ hostnamePlaceholder = m.container_hostname_placeholder(),
onSubmit
}: {
mode: 'create' | 'edit';
@@ -42,6 +43,7 @@
rows: ContainerFormRows;
submitting?: boolean;
cancelHref?: string;
+ hostnamePlaceholder?: string;
onSubmit: () => void;
} = $props();
@@ -118,9 +120,11 @@
function handleSubmit() {
onSubmit();
- // Required fields live on the general tab; bring failed validation into view.
+ // Bring failed validation into view on the correct tab.
if (inputs.name.error || inputs.image.error) {
selectedTab = 'general';
+ } else if (inputs.hostname.error) {
+ selectedTab = 'networks';
}
}
@@ -303,6 +307,13 @@
<div class="space-y-4">
{@render groupTitle(m.resource_networks_cap(), m.aliases_note())}
<NetworkAttachmentEditor bind:rows={rows.networks} networks={networkNames} disabled={submitting} />
+ <FormInput
+ label={m.hostname()}
+ type="text"
+ placeholder={hostnamePlaceholder}
+ disabled={submitting}
+ bind:input={inputs.hostname}
+ />
</div>
</Tabs.Content>
diff --git a/frontend/src/lib/types/docker.ts b/frontend/src/lib/types/docker.ts
index de0955c18..3ac1acb9f 100644
--- a/frontend/src/lib/types/docker.ts
+++ b/frontend/src/lib/types/docker.ts
@@ -115,6 +115,7 @@ export interface ContainerEditRequest {
image?: string;
workingDir?: string;
user?: string;
+ hostname?: string;
command?: string[];
entrypoint?: string[];
environment?: string[];
@@ -156,6 +157,7 @@ export interface ContainerEditConfigDto {
entrypoint?: string[];
workingDir?: string;
user?: string;
+ hostname?: string;
environment?: string[];
labels?: Record<string, string>;
healthcheck?: ContainerHealthcheckCreate;
@@ -296,6 +298,7 @@ export interface ContainerConfigDto {
entrypoint?: string[];
workingDir?: string;
user?: string;
+ hostname?: string;
healthcheck?: ContainerHealthcheckDto;
}
diff --git a/frontend/src/lib/utils/docker.ts b/frontend/src/lib/utils/docker.ts
index 62ca4950f..92a50c352 100644
--- a/frontend/src/lib/utils/docker.ts
+++ b/frontend/src/lib/utils/docker.ts
@@ -1,7 +1,7 @@
import type { Temporal } from 'temporal-polyfill';
import { m } from '#lib/paraglide/messages.js';
-import type { ContainerStats, ContainerSummaryDto } from '#lib/types/docker.js';
+import type { ContainerDetailsDto, ContainerStats, ContainerSummaryDto } from '#lib/types/docker.js';
import type { Environment, EnvironmentStatus } from '#lib/types/environment.js';
import type { VulnerabilityScanSummary } from '#lib/types/environment.js';
import type { SearchPaginationSortRequest } from '#lib/types/shared.js';
@@ -81,6 +81,14 @@ export function getContainerIpAddresses(container: ContainerSummaryDto): string[
return ipAddresses;
}
+// Docker falls back to the container's short ID, so only a hostname that was asked for is worth showing.
+export function getCustomHostname(container: Pick<ContainerDetailsDto, 'id' | 'config'>): string | undefined {
+ const hostname = container.config?.hostname?.trim();
+ if (!hostname) return undefined;
+ const shortId = container.id.length >= 12 ? container.id.slice(0, 12) : null;
+ return hostname === shortId ? undefined : hostname;
+}
+
// --- Swarm service mode helpers ---
export type SwarmServiceModeBadgeVariant = 'green' | 'blue' | 'amber' | 'purple' | 'gray';
diff --git a/frontend/src/routes/(app)/containers/[containerId]/+page.svelte b/frontend/src/routes/(app)/containers/[containerId]/+page.svelte
index d44314cc3..e7a1f416e 100644
--- a/frontend/src/routes/(app)/containers/[containerId]/+page.svelte
+++ b/frontend/src/routes/(app)/containers/[containerId]/+page.svelte
@@ -43,7 +43,7 @@
import { runContainerLifecycleAction, confirmAndUpdateContainer } from '#lib/utils/container-actions.js';
import { isAutoUpdateLabelDisabled } from '#lib/utils/container-auto-update.js';
import { createContainerUpdateActivityTracker } from '#lib/utils/container-update-activities.js';
- import { calculateMemoryUsage, getThemedIconUrl } from '#lib/utils/docker.js';
+ import { calculateMemoryUsage, getCustomHostname, getThemedIconUrl } from '#lib/utils/docker.js';
import { environmentHref, listScopes } from '#lib/utils/environments.js';
import { bytes } from '#lib/utils/formatting.js';
import { tryCatch } from '#lib/utils/try-catch.js';
@@ -147,7 +147,9 @@
const hasNetworks = $derived(
!!(container?.networkSettings?.networks && Object.keys(container.networkSettings.networks).length > 0)
);
- const showNetworkTab = $derived(hasNetworks || hasPorts);
+ // A container with a hostname but no networks or ports still has something to show here.
+ const hasCustomHostname = $derived(!!(container && getCustomHostname(container)));
+ const showNetworkTab = $derived(hasNetworks || hasPorts || hasCustomHostname);
const hasMounts = $derived(!!(container?.mounts && container.mounts.length > 0));
const currentEnvId = $derived(data.envId);
const canViewLogs = $derived(hasPermission('containers:logs', currentEnvId));
diff --git a/frontend/src/routes/(app)/containers/[containerId]/edit/+page.svelte b/frontend/src/routes/(app)/containers/[containerId]/edit/+page.svelte
index 87cbbfa76..649831ba8 100644
--- a/frontend/src/routes/(app)/containers/[containerId]/edit/+page.svelte
+++ b/frontend/src/routes/(app)/containers/[containerId]/edit/+page.svelte
@@ -8,6 +8,7 @@
import { openConfirmDialog } from '#lib/components/confirm-dialog/index.js';
import {
containerFormSchema,
+ editContainerFormSchema,
formValuesFromEditConfig,
rowsFromEditConfig,
toEditRequest
@@ -28,7 +29,10 @@
const queryClient = useQueryClient();
// The form is intentionally seeded once from the load-time snapshot.
// svelte-ignore state_referenced_locally
- const form = createForm<typeof containerFormSchema>(containerFormSchema, formValuesFromEditConfig(data.editConfig));
+ const form = createForm<typeof containerFormSchema>(
+ editContainerFormSchema(data.editConfig.hostname),
+ formValuesFromEditConfig(data.editConfig)
+ );
let rows = $state(untrack(() => rowsFromEditConfig(data.editConfig)));
const editContainerMutation = createMutation(() => ({
@@ -90,6 +94,7 @@
bind:rows
cancelHref={environmentHref(`/containers/${data.containerId}`, data.envId)}
environmentId={data.envId}
+ hostnamePlaceholder={data.editConfig.id.slice(0, 12)}
submitting={editContainerMutation.isPending}
onSubmit={handleSubmit}
/>
diff --git a/frontend/src/routes/(app)/containers/components/container-network.svelte b/frontend/src/routes/(app)/containers/components/container-network.svelte
index 1208cd9b4..5753679b4 100644
--- a/frontend/src/routes/(app)/containers/components/container-network.svelte
+++ b/frontend/src/routes/(app)/containers/components/container-network.svelte
@@ -1,6 +1,6 @@
<script lang="ts">
import { refreshAll } from '$app/navigation';
- import { createQuery } from '@tanstack/svelte-query';
+ import { createQuery, useQueryClient } from '@tanstack/svelte-query';
import { toast } from 'svelte-sonner';
import { ArcaneButton } from '#lib/components/arcane-button/index.js';
@@ -16,6 +16,7 @@
import type { ContainerDetailsDto } from '#lib/types/docker.js';
import { handleApiResultWithCallbacks } from '#lib/utils/api.js';
import { hasPermission } from '#lib/utils/auth.js';
+ import { getCustomHostname } from '#lib/utils/docker.js';
import { tryCatch } from '#lib/utils/try-catch.js';
interface Props {
@@ -25,7 +26,9 @@
let { container, environmentId }: Props = $props();
+ const queryClient = useQueryClient();
const envId = $derived(environmentId);
+ const customHostname = $derived(getCustomHostname(container));
const canConnect = $derived(hasPermission('networks:connect', envId));
const canDisconnect = $derived(hasPermission('networks:disconnect', envId));
@@ -50,6 +53,13 @@
.map((name) => ({ value: name, label: name }))
);
+ // The loader reads the container through the query cache, so a refresh within its stale window would
+ // reuse the detail fetched just before the change and leave the network list on screen out of date.
+ async function refreshContainer(targetEnvId: string, targetContainerId: string) {
+ await queryClient.invalidateQueries({ queryKey: queryKeys.containers.detail(targetEnvId, targetContainerId) });
+ await refreshAll();
+ }
+
async function handleConnect() {
if (!connectNetwork) return;
connectPending = true;
@@ -73,7 +83,7 @@
connectNetwork = '';
connectAliases = '';
connectIp = '';
- await refreshAll();
+ await refreshContainer(envId, container.id);
})()
);
await handleApiResultWithCallbacks({ result: operationResult, message: m.network_connect_failed() });
@@ -102,7 +112,7 @@
target.environmentId
);
toast.success(m.network_disconnect_success());
- await refreshAll();
+ await refreshContainer(target.environmentId, target.containerId);
})()
);
await handleApiResultWithCallbacks({ result: operationResult, message: m.network_disconnect_failed() });
@@ -318,6 +328,20 @@
</div>
</div>
{/if}
+
+ {#if customHostname}
+ <Card.Root variant="outlined" size="sm" class="mt-4">
+ <Card.Content class="flex flex-col">
+ <div class="mb-2 text-xs font-semibold text-muted-foreground">{m.hostname()}</div>
+ <div
+ class="cursor-pointer font-mono text-sm font-medium break-all text-foreground select-all"
+ title={m.common_click_to_select()}
+ >
+ {customHostname}
+ </div>
+ </Card.Content>
+ </Card.Root>
+ {/if}
</Card.Content>
</Card.Root>
</div>
diff --git a/types/container/container.go b/types/container/container.go
index a40e44adc..57ff82654 100644
--- a/types/container/container.go
+++ b/types/container/container.go
@@ -758,6 +758,11 @@ type Config struct {
// Required: false
User string `json:"user,omitempty"`
+ // Hostname of the container.
+ //
+ // Required: false
+ Hostname string `json:"hostname,omitempty"`
+
// Healthcheck is the container's healthcheck configuration.
//
// Required: false
@@ -1313,6 +1318,7 @@ func mapInspectConfig(config *container.Config) (Config, map[string]string, stri
Entrypoint: append([]string{}, config.Entrypoint...),
WorkingDir: config.WorkingDir,
User: config.User,
+ Hostname: config.Hostname,
}
if hc := config.Healthcheck; hc != nil {
@@ -1552,6 +1558,11 @@ type Edit struct {
// Required: false
User *string `json:"user,omitempty"`
+ // Hostname for the container. An empty value clears it.
+ //
+ // Required: false
+ Hostname *string `json:"hostname,omitempty"`
+
// Command to run in the container.
//
// Required: false
@@ -1728,6 +1739,11 @@ type EditConfig struct {
// Required: false
User string `json:"user,omitempty"`
+ // Hostname of the container, omitted when it is the Docker default.
+ //
+ // Required: false
+ Hostname string `json:"hostname,omitempty"`
+
// Environment variables of the container.
//
// Required: false
@@ -1791,6 +1807,9 @@ func NewEditConfigFromInspect(c *container.InspectResponse, isCompose, editDisab
cfg.Entrypoint = append([]string{}, c.Config.Entrypoint...)
cfg.WorkingDir = c.Config.WorkingDir
cfg.User = c.Config.User
+ if len(c.ID) < 12 || c.Config.Hostname != c.ID[:12] {
+ cfg.Hostname = c.Config.Hostname
+ }
cfg.Environment = append([]string{}, c.Config.Env...)
cfg.Labels = c.Config.Labels
cfg.ComposeProject = c.Config.Labels["com.docker.compose.project"]