Skip to content

Instantly share code, notes, and snippets.

@developer-guy
Created October 25, 2022 09:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save developer-guy/20307ff21341b4e95642b43a36615bde to your computer and use it in GitHub Desktop.
Save developer-guy/20307ff21341b4e95642b43a36615bde to your computer and use it in GitHub Desktop.
Programmatically run container registry based on Docker's reference implementation distribution/distribution
package main
import (
"context"
"fmt"
"os"
"os/signal"
"syscall"
"time"
"github.com/distribution/distribution/v3/configuration"
"github.com/distribution/distribution/v3/registry"
_ "github.com/distribution/distribution/v3/registry/auth/htpasswd"
_ "github.com/distribution/distribution/v3/registry/storage/driver/inmemory"
"github.com/phayes/freeport"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Registry config
config := &configuration.Configuration{}
port, err := freeport.GetFreePort()
if err != nil {
panic(fmt.Errorf("failed to get free port: %s", err))
}
dockerReg := fmt.Sprintf("localhost:%d", port)
config.HTTP.Addr = fmt.Sprintf("127.0.0.1:%d", port)
config.HTTP.DrainTimeout = time.Duration(10) * time.Second
config.Storage = map[string]configuration.Parameters{"inmemory": map[string]interface{}{}}
dockerRegistry, err := registry.NewRegistry(ctx, config)
if err != nil {
panic(fmt.Errorf("failed to create docker registry: %w", err))
}
c := make(chan os.Signal, 2)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
// Start Docker registry
go dockerRegistry.ListenAndServe()
fmt.Println("registry server started at:", dockerReg)
<-c
fmt.Println("shutting down the registry server")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment