Skip to content

Modern Docker Management, Designed for Everyone

feat: add support for filtering containers and projects by labels (#3874)

Kyle Mendell5dfd281c628b
diff --git a/backend/internal/container/handler.go b/backend/internal/container/handler.go
index 1da544862..463ce4f0c 100644
--- a/backend/internal/container/handler.go
+++ b/backend/internal/container/handler.go
@@ -63,6 +63,7 @@ type ListContainersInput struct {
IncludeInternal bool `query:"includeInternal" default:"false" doc:"Include internal containers"`
Updates string `query:"updates" doc:"Filter by update status (has_update, up_to_date, error, unknown)"`
Standalone string `query:"standalone" doc:"Filter standalone containers only (true/false)"`
+ Label string `query:"label" doc:"Filter by label key or key=value"`
}
type ListContainersOutput struct {
@@ -313,6 +314,9 @@ func (h *ContainerHandler) ListContainers(ctx context.Context, input *ListContai
if input.Standalone != "" {
params.Filters["standalone"] = input.Standalone
}
+ if input.Label != "" {
+ params.Filters["label"] = input.Label
+ }
result, err := h.containerService.ListContainersPaginated(ctx, params, true, input.IncludeInternal, input.GroupBy)
if err != nil {
diff --git a/backend/internal/container/service.go b/backend/internal/container/service.go
index 3d3239535..7622a72c2 100644
--- a/backend/internal/container/service.go
+++ b/backend/internal/container/service.go
@@ -1915,6 +1915,19 @@ func (s *ContainerService) buildContainerFilterAccessors() []pagination.FilterAc
}
},
},
+ {
+ Key: "label",
+ NoSplit: true,
+ Fn: func(c containertypes.Summary, filterValue string) bool {
+ key, value, hasValue := strings.Cut(filterValue, "=")
+ key = strings.TrimSpace(key)
+ if key == "" {
+ return true
+ }
+ actual, ok := c.Labels[key]
+ return ok && (!hasValue || actual == value)
+ },
+ },
}
}
diff --git a/backend/internal/container/service_test.go b/backend/internal/container/service_test.go
index b15848357..493752459 100644
--- a/backend/internal/container/service_test.go
+++ b/backend/internal/container/service_test.go
@@ -185,6 +185,38 @@ func TestBuildContainerFilterAccessors_FiltersStandaloneContainers(t *testing.T)
require.Equal(t, int64(1), result.TotalCount)
}
+func TestBuildContainerFilterAccessors_FiltersByLabel(t *testing.T) {
+ service := &ContainerService{}
+ items := []containertypes.Summary{
+ {ID: "tagged", Labels: map[string]string{"heal": "true", "tags": "a,b"}},
+ {ID: "other", Labels: map[string]string{"heal": "false"}},
+ {ID: "bare", Labels: map[string]string{}},
+ }
+ config := pagination.Config[containertypes.Summary]{FilterAccessors: service.buildContainerFilterAccessors()}
+
+ tests := []struct {
+ name string
+ filter string
+ want []string
+ }{
+ {name: "key only", filter: "heal", want: []string{"tagged", "other"}},
+ {name: "key and value", filter: "heal=true", want: []string{"tagged"}},
+ {name: "missing key", filter: "missing", want: nil},
+ {name: "value containing comma", filter: "tags=a,b", want: []string{"tagged"}},
+ {name: "blank is a no-op", filter: " ", want: []string{"tagged", "other", "bare"}},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ result := config.SearchOrderAndPaginate(items, pagination.QueryParams{Filters: map[string]string{"label": tt.filter}})
+ var got []string
+ for _, item := range result.Items {
+ got = append(got, item.ID)
+ }
+ require.Equal(t, tt.want, got)
+ })
+ }
+}
+
func TestBuildCleanNetworkingConfigInternalPreservesEndpointSettings(t *testing.T) {
containerInspect := container.InspectResponse{
NetworkSettings: &container.NetworkSettings{
diff --git a/backend/internal/project/handler.go b/backend/internal/project/handler.go
index 9a0c79503..2c9307448 100644
--- a/backend/internal/project/handler.go
+++ b/backend/internal/project/handler.go
@@ -55,6 +55,7 @@ type ListProjectsInput struct {
Updates string `query:"updates" doc:"Filter by update status (has_update, up_to_date, error, unknown)"`
Archived string `query:"archived" doc:"Archived filter: 'true' (only archived), 'all' (include archived). Default excludes archived."`
Tags string `query:"tags" doc:"Filter by tag names (comma-separated, OR semantics)"`
+ Label string `query:"label" doc:"Filter by container label key or key=value on any running service"`
}
type GetProjectStatusCountsInput struct {
@@ -393,6 +394,9 @@ func (h *ProjectHandler) ListProjects(ctx context.Context, input *ListProjectsIn
if input.Tags != "" {
params.Filters["tags"] = input.Tags
}
+ if input.Label != "" {
+ params.Filters["label"] = input.Label
+ }
projects, paginationResp, err := h.projectService.ListProjects(ctx, params)
if err != nil {
diff --git a/backend/internal/project/project_listing.go b/backend/internal/project/project_listing.go
index 3fbad90ae..91194bc88 100644
--- a/backend/internal/project/project_listing.go
+++ b/backend/internal/project/project_listing.go
@@ -184,15 +184,17 @@ func (s *ProjectService) ListProjects(ctx context.Context, params pagination.Que
updatesFilter := ""
archivedFilter := ""
tagsFilter := ""
+ labelFilter := ""
if params.Filters != nil {
statusFilter = strings.TrimSpace(params.Filters["status"])
updatesFilter = strings.TrimSpace(params.Filters["updates"])
archivedFilter = strings.TrimSpace(params.Filters["archived"])
tagsFilter = strings.TrimSpace(params.Filters["tags"])
+ labelFilter = strings.TrimSpace(params.Filters["label"])
}
query = applyProjectArchivedDBFilterInternal(query, archivedFilter)
query = applyProjectTagsDBFilterInternal(query, tagsFilter)
- if statusFilter != "" || updatesFilter != "" {
+ if statusFilter != "" || updatesFilter != "" || labelFilter != "" {
return s.listProjectsWithDerivedFiltersInternal(ctx, params, query)
}
@@ -679,6 +681,27 @@ func (s *ProjectService) buildProjectDerivedPaginationConfigInternal() paginatio
buildProjectStatusFilterAccessorInternal(),
buildProjectUpdatesFilterAccessorInternal(),
buildProjectArchivedFilterAccessorInternal(),
+ buildProjectLabelFilterAccessorInternal(),
+ },
+ }
+}
+
+func buildProjectLabelFilterAccessorInternal() pagination.FilterAccessor[project.Details] {
+ return pagination.FilterAccessor[project.Details]{
+ Key: "label",
+ NoSplit: true,
+ Fn: func(p project.Details, filterValue string) bool {
+ key, value, hasValue := strings.Cut(filterValue, "=")
+ key = strings.TrimSpace(key)
+ if key == "" {
+ return true
+ }
+ for _, service := range p.RuntimeServices {
+ if actual, ok := service.ContainerLabels[key]; ok && (!hasValue || actual == value) {
+ return true
+ }
+ }
+ return false
},
}
}
diff --git a/backend/internal/project/service_test.go b/backend/internal/project/service_test.go
index b0efbc1a2..e2d7d27b6 100644
--- a/backend/internal/project/service_test.go
+++ b/backend/internal/project/service_test.go
@@ -3708,6 +3708,40 @@ func TestProjectService_GetProjectDetails_PopulatesRuntimeServicesFromComposePs(
assert.Equal(t, "projecta-server-1", details.RuntimeServices[0].ContainerName)
}
+func TestBuildProjectLabelFilterAccessorInternal(t *testing.T) {
+ items := []projecttypes.Details{
+ {ID: "tagged", RuntimeServices: []projecttypes.RuntimeService{
+ {Name: "web", ContainerLabels: map[string]string{"heal": "true"}},
+ {Name: "db", ContainerLabels: map[string]string{"tags": "a,b"}},
+ }},
+ {ID: "other", RuntimeServices: []projecttypes.RuntimeService{{Name: "web", ContainerLabels: map[string]string{"heal": "false"}}}},
+ {ID: "down"},
+ }
+ config := pagination.Config[projecttypes.Details]{FilterAccessors: []pagination.FilterAccessor[projecttypes.Details]{buildProjectLabelFilterAccessorInternal()}}
+
+ tests := []struct {
+ name string
+ filter string
+ want []string
+ }{
+ {name: "key only", filter: "heal", want: []string{"tagged", "other"}},
+ {name: "key and value", filter: "heal=true", want: []string{"tagged"}},
+ {name: "missing key", filter: "missing", want: nil},
+ {name: "value containing comma", filter: "tags=a,b", want: []string{"tagged"}},
+ {name: "blank is a no-op", filter: " ", want: []string{"tagged", "other", "down"}},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ result := config.SearchOrderAndPaginate(items, pagination.QueryParams{Filters: map[string]string{"label": tt.filter}})
+ var got []string
+ for _, item := range result.Items {
+ got = append(got, item.ID)
+ }
+ require.Equal(t, tt.want, got)
+ })
+ }
+}
+
func TestProjectService_ListProjects_FiltersByUpdateStatus(t *testing.T) {
db := setupProjectTestDB(t)
ctx := context.Background()
diff --git a/backend/pkg/pagination/filters.go b/backend/pkg/pagination/filters.go
index c1fe373bb..9d926e3ce 100644
--- a/backend/pkg/pagination/filters.go
+++ b/backend/pkg/pagination/filters.go
@@ -11,6 +11,8 @@ type FilterResult[T any] struct {
type FilterAccessor[T any] struct {
Key string
Fn func(item T, filterValue string) bool
+ // NoSplit passes the raw value through instead of treating commas as alternatives.
+ NoSplit bool
}
type Config[T any] struct {
@@ -108,7 +110,7 @@ func getAccessor[T any](key string, accessors []FilterAccessor[T]) *FilterAccess
}
func matchValue[T any](item T, value string, accessor *FilterAccessor[T]) bool {
- if strings.Contains(value, ",") {
+ if !accessor.NoSplit && strings.Contains(value, ",") {
values := strings.SplitSeq(value, ",")
for v := range values {
v = strings.TrimSpace(v)
diff --git a/cli/pkg/containers/cmd.go b/cli/pkg/containers/cmd.go
index d575ef1fa..968a9c4e4 100644
--- a/cli/pkg/containers/cmd.go
+++ b/cli/pkg/containers/cmd.go
@@ -28,6 +28,7 @@ var (
containersAll bool
containersUpdatesFilter string
containersStandalone string
+ containersLabelFilter string
containersIncludeInternal bool
containersDeleteVolumes bool
forceFlag bool
@@ -98,6 +99,9 @@ func runContainersList(cmd *cobra.Command, forceHasUpdateFilter bool) error {
if updatesFilter != "" {
query.Set("updates", updatesFilter)
}
+ if labelFilter := strings.TrimSpace(containersLabelFilter); labelFilter != "" {
+ query.Set("label", labelFilter)
+ }
spec := cmdutil.ListSpec[container.Summary]{
Resource: "containers",
@@ -557,6 +561,7 @@ func init() {
containersListCmd.Flags().BoolVarP(&containersAll, "all", "a", false, cmdutil.AllFlagUsage)
containersListCmd.Flags().StringVar(&containersUpdatesFilter, "updates", "", "Filter by update status (has_update, up_to_date, error, unknown)")
containersListCmd.Flags().StringVar(&containersStandalone, "standalone", "", "Filter standalone containers only (true/false)")
+ containersListCmd.Flags().StringVar(&containersLabelFilter, "label", "", "Filter by label (key or key=value)")
containersListCmd.Flags().BoolVar(&containersIncludeInternal, "include-internal", false, "Include Arcane-internal containers")
containersListCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
containersUpdatesCmd.Flags().IntVarP(&containersLimit, "limit", "n", 20, "Number of containers to show")
diff --git a/cli/pkg/projects/cmd.go b/cli/pkg/projects/cmd.go
index 1653eadbb..68ebc2987 100644
--- a/cli/pkg/projects/cmd.go
+++ b/cli/pkg/projects/cmd.go
@@ -35,6 +35,7 @@ var (
projectsUpdatesFilter string
projectsStatusFilter string
projectsArchivedFilter string
+ projectsLabelFilter string
forceFlag bool
jsonOutput bool
destroyRemoveFiles bool
@@ -92,6 +93,9 @@ func runProjectsList(cmd *cobra.Command, forceHasUpdateFilter bool) error {
if projectsStatusFilter != "" {
query.Set("status", projectsStatusFilter)
}
+ if labelFilter := strings.TrimSpace(projectsLabelFilter); labelFilter != "" {
+ query.Set("label", labelFilter)
+ }
// The server excludes archived projects unless asked, so --all has to opt
// into them explicitly to actually mean "everything".
switch {
@@ -666,6 +670,7 @@ func init() {
listCmd.Flags().StringVar(&projectsUpdatesFilter, "updates", "", "Filter by update status (has_update, up_to_date, error, unknown)")
listCmd.Flags().StringVar(&projectsStatusFilter, "status", "", "Filter by status (comma-separated: running, stopped, partially running)")
listCmd.Flags().StringVar(&projectsArchivedFilter, "archived", "", "Archived filter: 'true' for archived only, 'all' to include archived")
+ listCmd.Flags().StringVar(&projectsLabelFilter, "label", "", "Filter by container label (key or key=value)")
listCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
updatesCmd.Flags().IntVarP(&limitFlag, "limit", "n", 20, "Number of projects to show")
updatesCmd.Flags().IntVar(&startFlag, "start", 0, cmdutil.StartFlagUsage)
diff --git a/frontend/messages/en.json b/frontend/messages/en.json
index f38f95b93..63f29327b 100644
--- a/frontend/messages/en.json
+++ b/frontend/messages/en.json
@@ -108,6 +108,7 @@
"common_scope": "Scope",
"common_mountpoint": "Mountpoint",
"common_labels": "Labels",
+ "label_filter_hint": "key or key=value",
"common_driver_options": "Driver Options",
"common_back_to": "Back to {resource}",
"common_back": "Back",
diff --git a/frontend/src/lib/components/arcane-table/arcane-table-text-filter.svelte b/frontend/src/lib/components/arcane-table/arcane-table-text-filter.svelte
new file mode 100644
index 000000000..8de591b6e
--- /dev/null
+++ b/frontend/src/lib/components/arcane-table/arcane-table-text-filter.svelte
@@ -0,0 +1,88 @@
+<script lang="ts">
+ import * as Popover from '#lib/components/ui/popover/index.js';
+ import { ArcaneButton } from '#lib/components/arcane-button/index.js';
+ import { Input } from '#lib/components/ui/input/index.js';
+ import { Separator } from '#lib/components/ui/separator/index.js';
+ import { cn } from '#lib/utils.js';
+ import { m } from '#lib/paraglide/messages.js';
+ import { FilterIcon } from '#lib/icons/index.js';
+
+ type FilterableColumn = {
+ getFilterValue: () => unknown;
+ setFilterValue: (value: unknown) => void;
+ };
+
+ let {
+ column,
+ title,
+ placeholder
+ }: {
+ column: FilterableColumn;
+ title: string;
+ placeholder: string;
+ } = $props();
+
+ let open = $state(false);
+ const currentValue = $derived(String(column?.getFilterValue() ?? ''));
+ let draft = $derived(currentValue);
+
+ function apply() {
+ const value = draft.trim();
+ if (value === currentValue) return;
+ column?.setFilterValue(value || undefined);
+ }
+</script>
+
+<Popover.Root
+ bind:open
+ onOpenChange={(next) => {
+ if (!next) apply();
+ }}
+>
+ <Popover.Trigger>
+ {#snippet child({ props })}
+ <ArcaneButton
+ {...props}
+ action="base"
+ tone="ghost"
+ size="sm"
+ icon={FilterIcon}
+ customLabel={title}
+ class={cn(
+ 'h-8 border border-dashed border-input hover:bg-card/60 hover:text-inherit',
+ currentValue && 'border-solid border-primary/40 bg-primary/10 text-foreground'
+ )}
+ data-testid={`facet-${title.toLowerCase()}-trigger`}
+ >
+ {#if currentValue}
+ <Separator orientation="vertical" class="mx-1 h-4" />
+ <span class="max-w-40 truncate text-xs font-medium text-muted-foreground">{currentValue}</span>
+ {/if}
+ </ArcaneButton>
+ {/snippet}
+ </Popover.Trigger>
+ <Popover.Content class="w-[240px] p-2" align="start" data-testid={`facet-${title.toLowerCase()}-content`}>
+ <div class="flex flex-col gap-2">
+ <Input
+ {placeholder}
+ bind:value={draft}
+ onkeydown={(e) => {
+ if (e.key !== 'Enter') return;
+ apply();
+ open = false;
+ }}
+ class="h-8"
+ />
+ {#if currentValue}
+ <ArcaneButton
+ action="base"
+ tone="ghost"
+ size="sm"
+ customLabel={m.common_clear_filters()}
+ onclick={() => column?.setFilterValue(undefined)}
+ class="h-8 justify-center"
+ />
+ {/if}
+ </div>
+ </Popover.Content>
+</Popover.Root>
diff --git a/frontend/src/lib/components/arcane-table/arcane-table-toolbar.svelte b/frontend/src/lib/components/arcane-table/arcane-table-toolbar.svelte
index 6e1ef8dda..b47a0db2e 100644
--- a/frontend/src/lib/components/arcane-table/arcane-table-toolbar.svelte
+++ b/frontend/src/lib/components/arcane-table/arcane-table-toolbar.svelte
@@ -1,6 +1,7 @@
<script lang="ts" generics="TData extends Record<string, any>">
import type { ArcaneSvelteTable } from './table-features';
import DataTableFacetedFilter from './arcane-table-filter.svelte';
+ import DataTableTextFilter from './arcane-table-text-filter.svelte';
import DataTableViewOptions from './arcane-table-view-options.svelte';
import { Input } from '#lib/components/ui/input/index.js';
import {
@@ -83,23 +84,26 @@
const typeColumnFilterOptions = $derived(typeColumn?.columnDef.meta?.filterOptions ?? []);
const tagsColumn = $derived(table.getAllColumns().some((col) => col.id === 'tags') ? table.getColumn('tags') : undefined);
const tagsColumnFilterOptions = $derived(tagsColumn?.columnDef.meta?.filterOptions ?? []);
+ const labelColumn = $derived(table.getAllColumns().some((col) => col.id === 'label') ? table.getColumn('label') : undefined);
const debouncedSetGlobal = debounced((v: string) => table.setGlobalFilter(v), 300);
const imageNameFilterOptionsFormatted = $derived(imageNameFilterOptions.map((name) => ({ label: name, value: name })));
const hasSelection = $derived(!selectionDisabled && (selectedIds?.length ?? 0) > 0);
const hasBulkActions = $derived(bulkActions && bulkActions.length > 0);
- // Check if any filter columns exist
const hasFilterColumns = $derived(
!withoutFilters &&
- (!!(typeColumn && typeColumnFilterOptions.length > 0) ||
- !!(tagsColumn && tagsColumnFilterOptions.length > 0) ||
- !!usageColumn ||
- !!updatesColumn ||
- !!severityColumn ||
- !!vulnSeverityColumn ||
- !!(imageNameColumn && imageNameFilterOptions.length > 0) ||
- !!(statusColumn && serviceCountColumn))
+ [
+ typeColumn && typeColumnFilterOptions.length > 0,
+ tagsColumn && tagsColumnFilterOptions.length > 0,
+ labelColumn,
+ usageColumn,
+ updatesColumn,
+ severityColumn,
+ vulnSeverityColumn,
+ imageNameColumn && imageNameFilterOptions.length > 0,
+ statusColumn && serviceCountColumn
+ ].some(Boolean)
);
const activeFilterCount = $derived(table.atoms.columnFilters.get().length);
</script>
@@ -111,6 +115,9 @@
{#if tagsColumn && tagsColumnFilterOptions.length > 0}
<DataTableFacetedFilter column={tagsColumn} title={m.common_tags()} options={tagsColumnFilterOptions} />
{/if}
+ {#if labelColumn}
+ <DataTableTextFilter column={labelColumn} title={m.common_labels()} placeholder={m.label_filter_hint()} />
+ {/if}
{#if usageColumn}
<DataTableFacetedFilter column={usageColumn} title={m.common_usage()} options={usageFilters} />
{/if}
diff --git a/frontend/src/routes/(app)/containers/container-table.svelte b/frontend/src/routes/(app)/containers/container-table.svelte
index 79c4f7708..3859b6371 100644
--- a/frontend/src/routes/(app)/containers/container-table.svelte
+++ b/frontend/src/routes/(app)/containers/container-table.svelte
@@ -303,7 +303,8 @@
{ accessorKey: 'status', title: m.common_status() },
{ accessorKey: 'networkSettings', id: 'ipAddress', title: m.containers_ip_address(), sortable: false, cell: IPAddressCell },
{ accessorKey: 'ports', title: m.common_ports(), sortable: !groupByProject, cell: PortsCell },
- { accessorKey: 'created', title: m.common_created(), sortable: !groupByProject, cell: CreatedCell }
+ { accessorKey: 'created', title: m.common_created(), sortable: !groupByProject, cell: CreatedCell },
+ { id: 'label', accessorFn: (row) => Object.keys(row.labels ?? {}).length, title: m.common_labels(), hidden: true }
] satisfies ColumnSpec<ContainerSummaryDto>[]);
const mobileFields = [
diff --git a/frontend/src/routes/(app)/projects/projects-table.svelte b/frontend/src/routes/(app)/projects/projects-table.svelte
index 2b3aa9b4c..ec82ecb13 100644
--- a/frontend/src/routes/(app)/projects/projects-table.svelte
+++ b/frontend/src/routes/(app)/projects/projects-table.svelte
@@ -193,7 +193,8 @@
cell: UpdatesCell
},
{ accessorKey: 'createdAt', title: m.common_created(), sortable: true, cell: CreatedCell },
- { accessorKey: 'serviceCount', title: m.services(), sortable: true }
+ { accessorKey: 'serviceCount', title: m.services(), sortable: true },
+ { id: 'label', accessorFn: () => '', title: m.common_labels(), hidden: true }
] satisfies ColumnSpec<Project>[]
);