Files
tiny-forge/internal/docker/network.go
T
alexei.dolgolyov 791cd4d6af
Build / build (push) Successful in 12m20s
feat: rename Docker Watcher to Tinyforge
Rebrand the project as Tinyforge to reflect its evolution from a Docker
container watcher into a self-hosted mini CI/deployment platform.

Rename covers: Go module path, Docker labels, DB/config filenames,
JWT issuer, Dockerfile binary, docker-compose, CI workflows, frontend
i18n, README with static sites docs, and all code comments.
2026-04-12 21:30:39 +03:00

56 lines
1.5 KiB
Go

package docker
import (
"context"
"fmt"
"github.com/moby/moby/api/types/network"
"github.com/moby/moby/client"
)
// EnsureNetwork creates a Docker network with the given name if it does not
// already exist. It returns the network ID in all cases.
func (c *Client) EnsureNetwork(ctx context.Context, networkName string) (string, error) {
// Check if the network already exists.
filterArgs := make(client.Filters).Add("name", networkName)
listResult, err := c.api.NetworkList(ctx, client.NetworkListOptions{
Filters: filterArgs,
})
if err != nil {
return "", fmt.Errorf("list networks for %s: %w", networkName, err)
}
// NetworkList with a name filter may return partial matches, so check exact name.
for _, n := range listResult.Items {
if n.Name == networkName {
return n.ID, nil
}
}
// Create the network.
resp, err := c.api.NetworkCreate(ctx, networkName, client.NetworkCreateOptions{
Driver: "bridge",
Labels: map[string]string{
LabelProject: "tinyforge",
},
})
if err != nil {
return "", fmt.Errorf("create network %s: %w", networkName, err)
}
return resp.ID, nil
}
// ConnectNetwork attaches a container to an existing network.
func (c *Client) ConnectNetwork(ctx context.Context, networkID string, containerID string) error {
_, err := c.api.NetworkConnect(ctx, networkID, client.NetworkConnectOptions{
Container: containerID,
EndpointConfig: &network.EndpointSettings{},
})
if err != nil {
return fmt.Errorf("connect container %s to network %s: %w", containerID, networkID, err)
}
return nil
}