### Install Registry Command with Go Get Source: https://github.com/docker/cli/blob/master/vendor/github.com/docker/distribution/BUILDING.md Installs the registry command-line tool using 'go get'. Ensure your GOPATH is set up correctly and the project is checked out in '$GOPATH/src/github.com/docker/distribution'. ```bash go get github.com/docker/distribution/cmd/registry ``` -------------------------------- ### Run Registry with Example Configuration Source: https://github.com/docker/cli/blob/master/vendor/github.com/docker/distribution/BUILDING.md Starts the registry server using the provided example configuration file. Observe the log messages to confirm it is running correctly. ```bash $GOPATH/bin/registry serve $GOPATH/src/github.com/docker/distribution/cmd/registry/config-example.yml ``` -------------------------------- ### Install and Inspect Plugin Logs Source: https://github.com/docker/cli/blob/master/docs/extend/_index.md Installs a sample volume plugin and shows the initial log output from the Docker daemon, indicating the plugin has started. ```console $ docker plugin install tiborvass/sample-volume-plugin INFO[0036] Starting... Found 0 volumes on startup plugin=f52a3df433b9aceee436eaada0752f5797aab1de47e5485f1690a073b860ff62 ``` -------------------------------- ### Connect a container to a network when it starts Source: https://github.com/docker/cli/blob/master/docs/reference/commandline/network_connect.md This example demonstrates how to use the `docker run --network` option to start a container and immediately connect it to a network. ```console docker run -itd --network=multi-host-network busybox ``` -------------------------------- ### Install blackfriday-tool Source: https://github.com/docker/cli/blob/master/vendor/github.com/russross/blackfriday/v2/README.md Install the blackfriday-tool command-line utility using 'go get'. This tool provides a standalone program for markdown file processing and also installs the blackfriday package. ```go go get github.com/russross/blackfriday-tool ``` -------------------------------- ### Install go.yaml.in/yaml/v3 Source: https://github.com/docker/cli/blob/master/vendor/go.yaml.in/yaml/v3/README.md Use `go get` to install the package. This command fetches and installs the specified Go package and its dependencies. ```bash go get go.yaml.in/yaml/v3 ``` -------------------------------- ### Install Cobra Library Source: https://github.com/docker/cli/blob/master/vendor/github.com/spf13/cobra/README.md Use 'go get' to install the latest version of the Cobra library. ```bash go get -u github.com/spf13/cobra@latest ``` -------------------------------- ### Install Blackfriday v2 Source: https://github.com/docker/cli/blob/master/vendor/github.com/russross/blackfriday/v2/README.md Use 'go get' to install Blackfriday v2 in module mode. Alternatively, import it in your package and run 'go get'. ```go go get github.com/russross/blackfriday/v2 ``` ```go import "github.com/russross/blackfriday/v2" ``` -------------------------------- ### Install gojsonschema Source: https://github.com/docker/cli/blob/master/vendor/github.com/xeipuuv/gojsonschema/README.md Use go get to install the gojsonschema library. ```bash go get github.com/xeipuuv/gojsonschema ``` -------------------------------- ### Go Mod File Example Source: https://github.com/docker/cli/blob/master/vendor/github.com/docker/cli-docs-tool/README.md Example of a go.mod file after adding the cli-docs-tool dependency. ```text module github.com/docker/buildx/docs go 1.16 require ( github.com/docker/cli-docs-tool v0.0.0 ) ``` -------------------------------- ### Install Mergo Source: https://github.com/docker/cli/blob/master/vendor/dario.cat/mergo/README.md Use this command to get the Mergo library. Then import it into your Go code. ```go go get dario.cat/mergo // use in your .go code import ( "dario.cat/mergo" ) ``` -------------------------------- ### Install and Run Local Go Doc Site Source: https://github.com/docker/cli/blob/master/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Installs and runs a local Go Doc site using pkgsite. Ensure you have the latest version installed. ```sh go install golang.org/x/pkgsite/cmd/pkgsite@latest pkgsite ``` -------------------------------- ### Install Graphemes Package Source: https://github.com/docker/cli/blob/master/vendor/github.com/clipperhouse/uax29/v2/graphemes/README.md Use go get to install the graphemes package. ```bash go get "github.com/clipperhouse/uax29/v2/graphemes" ``` -------------------------------- ### Install Pty Package Source: https://github.com/docker/cli/blob/master/vendor/github.com/creack/pty/README.md Install the pty package using go get. ```sh go get github.com/creack/pty ``` -------------------------------- ### Install mapstructure v2 Source: https://github.com/docker/cli/blob/master/vendor/github.com/go-viper/mapstructure/v2/README.md Use go get to install the mapstructure v2 library. This is the primary installation command. ```shell go get github.com/go-viper/mapstructure/v2 ``` -------------------------------- ### Start a container for exec examples Source: https://github.com/docker/cli/blob/master/docs/reference/commandline/container_exec.md Starts a detached, interactive, and TTY-enabled Alpine container with a shell. This is a prerequisite for running `docker exec` commands on it. ```console docker run --name mycontainer -d -i -t alpine /bin/sh ``` -------------------------------- ### Full Example of a Mux-based Server in Go Source: https://github.com/docker/cli/blob/master/vendor/github.com/gorilla/mux/README.md A complete, runnable example of a small server using Gorilla Mux. It sets up a router and a single handler for the root path. ```go package main import ( "net/http" "log" "github.com/gorilla/mux" ) func YourHandler(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Gorilla!\n")) } func main() { r := mux.NewRouter() // Routes consist of a path and a handler function. r.HandleFunc("/", YourHandler) // Bind to a port and pass our router in log.Fatal(http.ListenAndServe(":8000", r)) } ``` -------------------------------- ### Upgrade a plugin Source: https://github.com/docker/cli/blob/master/docs/reference/commandline/plugin_upgrade.md This example demonstrates the full lifecycle of installing, using, disabling, upgrading, and re-enabling a plugin. It shows how to upgrade the `vieux/sshfs` plugin to its latest version. ```console $ docker plugin install vieux/sshfs DEBUG=1 Plugin "vieux/sshfs:next" is requesting the following privileges: - network: [host] - device: [/dev/fuse] - capabilities: [CAP_SYS_ADMIN] Do you grant the above permissions? [y/N] y vieux/sshfs:next $ docker volume create -d vieux/sshfs:next -o sshcmd=root@1.2.3.4:/tmp/shared -o password=XXX sshvolume sshvolume $ docker run -it -v sshvolume:/data alpine sh -c "touch /data/hello" $ docker plugin disable -f vieux/sshfs:next viex/sshfs:next # Here docker volume ls doesn't show 'sshfsvolume', since the plugin is disabled $ docker volume ls DRIVER VOLUME NAME $ docker plugin upgrade vieux/sshfs:next vieux/sshfs:next Plugin "vieux/sshfs:next" is requesting the following privileges: - network: [host] - device: [/dev/fuse] - capabilities: [CAP_SYS_ADMIN] Do you grant the above permissions? [y/N] y Upgrade plugin vieux/sshfs:next to vieux/sshfs:next $ docker plugin enable vieux/sshfs:next viex/sshfs:next $ docker volume ls DRIVER VOLUME NAME viuex/sshfs:next sshvolume $ docker run -it -v sshvolume:/data alpine sh -c "ls /data" hello ``` -------------------------------- ### Install EBS Plugin from Registry Source: https://github.com/docker/cli/blob/master/docs/extend/EBS_volume.md Illustrates how to install a Docker plugin from a registry, providing necessary access key credentials for EBS. ```sh docker plugin install tiborvass/rexray-plugin EBS_ACCESSKEY=$AWS_ACCESSKEY EBS_SECRETKEY=$AWS_SECRETKEY ``` -------------------------------- ### Install Gorilla Mux Source: https://github.com/docker/cli/blob/master/vendor/github.com/gorilla/mux/README.md Use go get to install the latest version of the gorilla/mux package. Ensure your Go toolchain is correctly configured. ```sh go get -u github.com/gorilla/mux ``` -------------------------------- ### Install go-md2man Source: https://github.com/docker/cli/blob/master/vendor/github.com/cpuguy83/go-md2man/v2/README.md Install the go-md2man tool using `go install`. This command fetches the latest version and makes it available in your PATH. ```bash go install github.com/cpuguy83/go-md2man/v2@latest ``` -------------------------------- ### Example Docker Event Output Source: https://github.com/docker/cli/blob/master/docs/reference/commandline/system_events.md This is an example of the output generated by the `docker events` command when containers are created, started, and stopped. ```text 2017-01-05T00:35:58.859401177+08:00 container create 0fdb48addc82871eb34eb23a847cfd033dedd1a0a37bef2e6d9eb3870fc7ff37 (image=alpine:latest, name=test) 2017-01-05T00:36:04.703631903+08:00 network connect e2e1f5ceda09d4300f3a846f0acfaa9a8bb0d89e775eb744c5acecd60e0529e2 (container=0fdb...ff37, name=bridge, type=bridge) 2017-01-05T00:36:04.795031609+08:00 container start 0fdb...ff37 (image=alpine:latest, name=test) 2017-01-05T00:36:09.830268747+08:00 container kill 0fdb...ff37 (image=alpine:latest, name=test, signal=15) 2017-01-05T00:36:09.840186338+08:00 container die 0fdb...ff37 (exitCode=143, image=alpine:latest, name=test) 2017-01-05T00:36:09.880113663+08:00 network disconnect e2e...29e2 (container=0fdb...ff37, name=bridge, type=bridge) 2017-01-05T00:36:09.890214053+08:00 container stop 0fdb...ff37 (image=alpine:latest, name=test) ``` -------------------------------- ### Install uuid Package Source: https://github.com/docker/cli/blob/master/vendor/github.com/google/uuid/README.md Use this command to install the uuid package using go get. ```sh go get github.com/google/uuid ``` -------------------------------- ### Create a context from an existing DOCKER_HOST environment Source: https://github.com/docker/cli/blob/master/docs/reference/commandline/context_create.md This example demonstrates creating a new context named `my-context` after sourcing a setup script that configures the `DOCKER_HOST` environment variable. ```console $ source my-setup-script.sh $ docker context create my-context ``` -------------------------------- ### Full Docker Daemon Configuration Example (Windows) Source: https://github.com/docker/cli/blob/master/docs/reference/dockerd.md This snippet shows a comprehensive example of the allowed configuration options for the Docker daemon on Windows. It includes settings for containerd, networking, logging, and more. ```json { "authorization-plugins": [], "bridge": "", "containerd": "\\\\.\\pipe\\containerd-containerd", "containerd-namespace": "docker", "containerd-plugins-namespace": "docker-plugins", "data-root": "", "debug": true, "default-network-opts": {}, "default-runtime": "", "default-ulimits": {}, "dns": [], "dns-opts": [], "dns-search": [], "exec-opts": [], "experimental": false, "features": {}, "fixed-cidr": "", "group": "", "host-gateway-ip": "", "hosts": [], "insecure-registries": [], "labels": [], "log-driver": "", "log-format": "text", "log-level": "", "max-concurrent-downloads": 3, "max-concurrent-uploads": 5, "max-download-attempts": 5, "mtu": 0, "pidfile": "", "raw-logs": false, "registry-mirrors": [], "shutdown-timeout": 15, "storage-driver": "", "storage-opts": [], "swarm-default-advertise-addr": "", "tlscacert": "", "tlscert": "", "tlskey": "", "tlsverify": true } ``` -------------------------------- ### Tmpfs Mount Example Source: https://github.com/docker/cli/blob/master/man/docker-run.1.md Example of creating a tmpfs mount for a container, specifying the size and destination path. ```bash type=tmpfs,tmpfs-size=512M,destination=/path/in/container ``` -------------------------------- ### Bind Mount Example Source: https://github.com/docker/cli/blob/master/man/docker-run.1.md Example of attaching a bind mount to a container, specifying the source on the host and the destination within the container. ```bash type=bind,source=/path/on/host,destination=/path/in/container ``` -------------------------------- ### Install rclone plugin Source: https://github.com/docker/cli/blob/master/docs/extend/_index.md Installs the rclone plugin, prompting for necessary permissions. Ensure prerequisite directories exist on the host. ```console $ docker plugin install rclone/docker-volume-rclone --alias rclone Plugin "rclone/docker-volume-rclone" is requesting the following privileges: - network: [host] - mount: [/var/lib/docker-plugins/rclone/config] - mount: [/var/lib/docker-plugins/rclone/cache] - device: [/dev/fuse] - capabilities: [CAP_SYS_ADMIN] Do you grant the above permissions? [y/N] ``` -------------------------------- ### Install Golint for Make Builds Source: https://github.com/docker/cli/blob/master/vendor/github.com/docker/distribution/BUILDING.md Installs the 'golint' tool, which is a dependency for the 'make' command to perform linting during the build process. ```bash go get github.com/golang/lint/golint ``` -------------------------------- ### Example: Create and Restore Container Checkpoint Source: https://github.com/docker/cli/blob/master/docs/reference/commandline/checkpoint.md Demonstrates the workflow of creating a checkpoint for a running container and then restoring it. This example uses a busybox container that increments a counter, showing that the process state is preserved across checkpoint and restore operations. ```bash $ docker run --security-opt=seccomp:unconfined --name cr -d busybox /bin/sh -c 'i=0; while true; do echo $i; i=$(expr $i + 1); sleep 1; done' abc0123 $ docker checkpoint create cr checkpoint1 # $ docker start --checkpoint checkpoint1 cr abc0123 ``` -------------------------------- ### Volume Mount Example Source: https://github.com/docker/cli/blob/master/man/docker-run.1.md Example of attaching a named volume to a container, specifying the volume name, destination, and optional labels. ```bash type=volume,source=my-volume,destination=/path/in/container,volume-label="color=red" ``` -------------------------------- ### Create and Start an Interactive Container Source: https://github.com/docker/cli/blob/master/docs/reference/commandline/container_create.md Creates an interactive container with a pseudo-TTY attached, then starts and attaches to it. This is a two-step process equivalent to a single `docker run` command. ```console $ docker container create -i -t --name mycontainer alpine 6d8af538ec541dd581ebc2a24153a28329acb5268abe5ef868c1f1a261221752 $ docker container start --attach -i mycontainer / # echo hello world hello world ``` ```console $ docker run -it --name mycontainer2 alpine / # echo hello world hello world ``` -------------------------------- ### Install a plugin and set an environment variable Source: https://github.com/docker/cli/blob/master/docs/reference/commandline/plugin_install.md Installs the `vieux/sshfs` plugin, sets its `DEBUG` environment variable to `1`, prompts for privilege confirmation, and enables the plugin. ```console $ docker plugin install vieux/sshfs DEBUG=1 Plugin "vieux/sshfs" is requesting the following privileges: - network: [host] - device: [/dev/fuse] - capabilities: [CAP_SYS_ADMIN] Do you grant the above permissions? [y/N] y vieux/sshfs ``` -------------------------------- ### Example pretty output of service inspect Source: https://github.com/docker/cli/blob/master/docs/reference/commandline/service_inspect.md This is an example of the human-readable output produced when inspecting a Docker service with the --pretty option. ```console $ docker service inspect --pretty frontend ID: c8wgl7q4ndfd52ni6qftkvnnp Name: frontend Labels: - org.example.projectname=demo-app Service Mode: REPLICATED Replicas: 5 Placement: UpdateConfig: Parallelism: 0 On failure: pause Max failure ratio: 0 ContainerSpec: Image: nginx:alpine Resources: Networks: net1 Endpoint Mode: vip Ports: PublishedPort = 4443 Protocol = tcp TargetPort = 443 PublishMode = ingress ``` -------------------------------- ### Initialize Go Module and Get Tool Source: https://github.com/docker/cli/blob/master/vendor/github.com/docker/cli-docs-tool/README.md Set up a Go submodule to generate documentation. This involves initializing a Go module and fetching the documentation tool. ```console $ mkdir docs $ cd ./docs $ go mod init github.com/docker/buildx/docs $ go get github.com/docker/cli-docs-tool ``` -------------------------------- ### List plugins and push a sample plugin Source: https://github.com/docker/cli/blob/master/docs/reference/commandline/plugin_push.md First, list available plugins to identify the one you want to push. Then, use `docker plugin push` followed by the plugin name to share it to a registry. Ensure the plugin name includes the registry and tag if not using Docker Hub defaults. ```console $ docker plugin ls ID NAME DESCRIPTION ENABLED 69553ca1d456 user/plugin:latest A sample plugin for Docker false $ docker plugin push user/plugin ``` -------------------------------- ### Create a context with description and Docker endpoint details Source: https://github.com/docker/cli/blob/master/docs/reference/commandline/context_create.md This example demonstrates creating a context named `my-context` with a description and detailed Docker endpoint configuration including host, CA certificate, client certificate, and key. ```console $ docker context create my-context --description "some description" --docker "host=tcp://myserver:2376,ca=~/ca-file,cert=~/cert-file,key=~/key-file" ``` -------------------------------- ### Full Docker Daemon Configuration Example (Linux) Source: https://github.com/docker/cli/blob/master/docs/reference/dockerd.md This snippet shows a comprehensive example of the `daemon.json` configuration file for Linux. It includes settings for builder, default networks, logging, proxies, runtimes, and more. Ensure that options set here do not conflict with daemon startup flags. ```json { "allow-direct-routing": false, "authorization-plugins": [], "bip": "", "bip6": "", "bridge": "", "bridge-accept-fwmark": "", "builder": { "gc": { "enabled": true, "defaultReservedSpace": "10GB", "policy": [ { "maxUsedSpace": "512MB", "keepDuration": "48h", "filter": [ "type=source.local" ] }, { "reservedSpace": "10GB", "maxUsedSpace": "100GB", "keepDuration": "1440h" }, { "reservedSpace": "50GB", "minFreeSpace": "20GB", "maxUsedSpace": "200GB", "all": true } ] } }, "cgroup-parent": "", "containerd": "/run/containerd/containerd.sock", "containerd-namespace": "docker", "containerd-plugins-namespace": "docker-plugins", "data-root": "", "debug": true, "default-address-pools": [ { "base": "172.30.0.0/16", "size": 24 }, { "base": "172.31.0.0/16", "size": 24 } ], "default-cgroupns-mode": "private", "default-gateway": "", "default-gateway-v6": "", "default-network-opts": {}, "default-runtime": "runc", "default-shm-size": "64M", "default-ulimits": { "nofile": { "Hard": 64000, "Name": "nofile", "Soft": 64000 } }, "dns": [], "dns-opts": [], "dns-search": [], "exec-opts": [], "exec-root": "", "experimental": false, "features": { "cdi": true, "containerd-snapshotter": true }, "firewall-backend": "", "fixed-cidr": "", "fixed-cidr-v6": "", "group": "", "host-gateway-ip": "", "hosts": [], "proxies": { "http-proxy": "http://proxy.example.com:80", "https-proxy": "https://proxy.example.com:443", "no-proxy": "*.test.example.com,.example.org" }, "icc": false, "init": false, "init-path": "/usr/libexec/docker-init", "insecure-registries": [], "ip": "0.0.0.0", "ip-forward": false, "ip-masq": false, "iptables": false, "ip6tables": false, "ipv6": false, "labels": [], "live-restore": true, "log-driver": "json-file", "log-format": "text", "log-level": "", "log-opts": { "cache-disabled": "false", "cache-max-file": "5", "cache-max-size": "20m", "cache-compress": "true", "env": "os,customer", "labels": "somelabel", "max-file": "5", "max-size": "10m" }, "max-concurrent-downloads": 3, "max-concurrent-uploads": 5, "max-download-attempts": 5, "mtu": 0, "no-new-privileges": false, "node-generic-resources": [ "NVIDIA-GPU=UUID1", "NVIDIA-GPU=UUID2" ], "pidfile": "", "raw-logs": false, "registry-mirrors": [], "runtimes": { "cc-runtime": { "path": "/usr/bin/cc-runtime" }, "custom": { "path": "/usr/local/bin/my-runc-replacement", "runtimeArgs": [ "--debug" ] } }, "seccomp-profile": "", "selinux-enabled": false, "shutdown-timeout": 15, "storage-driver": "", "storage-opts": [], "swarm-default-advertise-addr": "", "tls": true, "tlscacert": "", "tlscert": "", "tlskey": "", "tlsverify": true, "userland-proxy": false, "userland-proxy-path": "/usr/libexec/docker-proxy", "userns-remap": "" } ``` -------------------------------- ### Install aec Package Source: https://github.com/docker/cli/blob/master/vendor/github.com/morikuni/aec/README.md Use 'go get' to install the aec package for your Go project. ```bash go get github.com/morikuni/aec ``` -------------------------------- ### Initialize Procfs and Get Stats Source: https://github.com/docker/cli/blob/master/vendor/github.com/prometheus/procfs/README.md Initializes the proc filesystem and retrieves CPU statistics. Use this to get started with basic system metrics. ```go fs, err := procfs.NewFS("/proc") stats, err := fs.Stat() ``` -------------------------------- ### Create a service Source: https://github.com/docker/cli/blob/master/docs/reference/commandline/service_rollback.md This example demonstrates creating a service with a single replica using nginx:alpine. This is a prerequisite for demonstrating the rollback functionality. ```bash docker service create --name my-service -p 8080:80 nginx:alpine ``` -------------------------------- ### List All Docker Containers using Go Client Source: https://github.com/docker/cli/blob/master/vendor/github.com/moby/moby/client/README.md Demonstrates how to create a Docker client from environment variables, set a custom User-Agent, and list all containers (both running and stopped) using the ContainerList API. Ensure the DOCKER_HOST environment variable is set. ```go package main import ( "context" "fmt" "github.com/moby/moby/client" ) func main() { // Create a new client with "client.FromEnv" (configuring the client // from commonly used environment variables such as DOCKER_HOST and // DOCKER_API_VERSION) and set a custom User-Agent. // // API-version negotiation is enabled by default to allow downgrading // the API version when connecting with an older daemon version. apiClient, err := client.New( client.FromEnv, client.WithUserAgent("my-application/1.0.0"), ) if err != nil { panic(err) } defer apiClient.Close() // List all containers (both stopped and running). result, err := apiClient.ContainerList(context.Background(), client.ContainerListOptions{ All: true, }) if err != nil { panic(err) } // Print each container's ID, status and the image it was created from. fmt.Printf("%s %-22s %s\n", "ID", "STATUS", "IMAGE") for _, ctr := range result.Items { fmt.Printf("%s %-22s %s\n", ctr.ID, ctr.Status, ctr.Image) } } ``` -------------------------------- ### Windows Volume Mount Example Source: https://github.com/docker/cli/blob/master/docs/reference/commandline/container_run.md Shows how to mount a volume on Windows using Windows-style path semantics. ```powershell PS C:\> docker run -v c:\foo:c:\dest microsoft/nanoserver cmd /s /c type c:\dest\somefile.txt Contents of file ``` ```powershell PS C:\> docker run -v c:\foo:d: microsoft/nanoserver cmd /s /c type d:\somefile.txt Contents of file ``` -------------------------------- ### Create New Configuration Instance Source: https://github.com/docker/cli/blob/master/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Creates a new configuration instance by applying options and setting default values. Includes validation logic. ```go // newConfig returns an appropriately configured config. func newConfig(options ...Option) config { // Set default values for config. config := config{/* […] */} for _, option := range options { config = option.apply(config) } // Perform any validation here. return config } ``` -------------------------------- ### Filter tasks by ID prefix Source: https://github.com/docker/cli/blob/master/docs/reference/commandline/stack_ps.md Use the 'id' filter to list tasks whose IDs start with a specific prefix. This example filters for tasks with IDs starting with 't' in the 'voting' stack. ```console $ docker stack ps -f "id=t" voting ``` -------------------------------- ### Exposing Windows Devices by Class GUID Source: https://github.com/docker/cli/blob/master/docs/reference/commandline/container_run.md This PowerShell example demonstrates how to make all devices implementing a specific interface class GUID available within a process-isolated Windows container, such as all COM ports. ```powershell PS C:\> docker run --device=class/86E0D1E0-8089-11D0-9CE4-08003E301F73 mcr.microsoft.com/windows/servercore:ltsc2019 ``` -------------------------------- ### Dockerfile Example for Squashing Source: https://github.com/docker/cli/blob/master/docs/reference/commandline/image_build.md A sample Dockerfile demonstrating file creation, modification, and removal, suitable for testing the --squash flag. ```dockerfile FROM busybox RUN echo hello > /hello RUN echo world >> /hello RUN touch remove_me /remove_me ENV HELLO=world RUN rm /remove_me ``` -------------------------------- ### ENTRYPOINT with Shell Execution Source: https://github.com/docker/cli/blob/master/man/Dockerfile.5.md This example demonstrates an ENTRYPOINT that always takes standard input and prints the number of lines. It executes in /bin/sh -c. ```Dockerfile FROM ubuntu ENTRYPOINT wc -l - ``` -------------------------------- ### Go JSON Pointer Usage Example Source: https://github.com/docker/cli/blob/master/vendor/github.com/xeipuuv/gojsonpointer/README.md Demonstrates how to use gojsonpointer to set, get, and delete values in a JSON document. Ensure the 'encoding/json' and 'fmt' packages are imported. ```go jsonText := `{ "name": "Bobby B", "occupation": { "title" : "King", "years" : 15, "heir" : "Joffrey B" } }` var jsonDocument map[string]interface{} json.Unmarshal([]byte(jsonText), &jsonDocument) //create a JSON pointer pointerString := "/occupation/title" pointer, _ := NewJsonPointer(pointerString) //SET a new value for the "title" in the document pointer.Set(jsonDocument, "Supreme Leader of Westeros") //GET the new "title" from the document title, _, _ := pointer.Get(jsonDocument) fmt.Println(title) //outputs "Supreme Leader of Westeros" //DELETE the "heir" from the document deletePointer := NewJsonPointer("/occupation/heir") deletePointer.Delete(jsonDocument) b, _ := json.Marshal(jsonDocument) fmt.Println(string(b)) //outputs `{"name":"Bobby B","occupation":{"title":"Supreme Leader of Westeros","years":15}}` ``` -------------------------------- ### Exposing Host Devices to a Container Source: https://github.com/docker/cli/blob/master/docs/reference/commandline/container_run.md This example demonstrates how to map host devices to specific paths within a container and lists the exposed devices to verify the mapping. ```console $ docker run -it --rm \ --device=/dev/sdc:/dev/xvdc \ --device=/dev/sdd \ --device=/dev/zero:/dev/foobar \ ubuntu ls -l /dev/{xvdc,sdd,foobar} brw-rw---- 1 root disk 8, 2 Feb 9 16:05 /dev/xvdc brw-rw---- 1 root disk 8, 3 Feb 9 16:05 /dev/sdd crw-rw-rw- 1 root root 1, 5 Feb 9 16:05 /dev/foobar ``` -------------------------------- ### Convert Markdown to Man Page with go tool Source: https://github.com/docker/cli/blob/master/vendor/github.com/cpuguy83/go-md2man/v2/README.md After installing with `go get -tool`, you can run go-md2man using `go tool`. This method is recommended for Go 1.24+. ```bash go tool go-md2man -in /path/to/markdownfile.md -out /manfile/output/path ``` -------------------------------- ### Example Output of Documentation Generation Source: https://github.com/docker/cli/blob/master/vendor/github.com/docker/cli-docs-tool/README.md Sample console output showing the progress of Markdown and YAML generation for various Docker buildx commands. ```console $ go run main.go INFO: Generating Markdown for "docker buildx bake" INFO: Generating Markdown for "docker buildx build" INFO: Generating Markdown for "docker buildx create" INFO: Generating Markdown for "docker buildx du" ... INFO: Generating YAML for "docker buildx uninstall" INFO: Generating YAML for "docker buildx use" INFO: Generating YAML for "docker buildx version" INFO: Generating YAML for "docker buildx" ``` -------------------------------- ### Enable Docker Authorization Plugins Source: https://github.com/docker/cli/blob/master/docs/reference/dockerd.md Install one or more authorization plugins when starting the Docker daemon using the --authorization-plugin option. The PLUGIN_ID can be the plugin's name or a path to its specification file. ```bash sudo dockerd --authorization-plugin=plugin1 --authorization-plugin=plugin2,... ``` -------------------------------- ### Create and List Volumes Source: https://github.com/docker/cli/blob/master/docs/reference/commandline/volume_ls.md Demonstrates creating two volumes and then listing them to show their presence. ```console $ docker volume create rosemary rosemary $ docker volume create tyler tyler $ docker volume ls DRIVER VOLUME NAME local rosemary local tyler ``` -------------------------------- ### Deterministic Testing Setup in Go Source: https://github.com/docker/cli/blob/master/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Set up the testing environment for deterministic results. This includes restoring global state, isolating the meter provider, setting environment variables, and resetting counters. ```go func TestObservability(t *testing.T) { // Restore state after test to ensure this does not affect other tests. prev := otel.GetMeterProvider() t.Cleanup(func() { otel.SetMeterProvider(prev) }) // Isolate the meter provider for deterministic testing reader := metric.NewManualReader() meterProvider := metric.NewMeterProvider(metric.WithReader(reader)) otel.SetMeterProvider(meterProvider) // Use t.Setenv to ensure environment variable is restored after test. t.Setenv("OTEL_GO_X_OBSERVABILITY", "true") // Reset component ID counter to ensure deterministic component names. componentIDCounter.Store(0) /* ... test code ... */ } ``` -------------------------------- ### Docker Run with nproc Ulimit Source: https://github.com/docker/cli/blob/master/docs/reference/commandline/container_run.md Demonstrates how setting the `nproc` ulimit can exhaust the process quota for a user, causing subsequent containers to fail. This example shows four containers attempting to start with `nproc=3` for the `daemon` user. ```console $ docker run -d -u daemon --ulimit nproc=3 busybox top $ docker run -d -u daemon --ulimit nproc=3 busybox top $ docker run -d -u daemon --ulimit nproc=3 busybox top $ docker run -d -u daemon --ulimit nproc=3 busybox top ``` -------------------------------- ### Check if a file descriptor is a terminal and get its size Source: https://github.com/docker/cli/blob/master/vendor/github.com/moby/term/README.md This example demonstrates how to check if a given file descriptor is associated with a terminal and, if so, retrieve its dimensions (height and width). It's useful for adapting terminal output based on available space. ```go package main import ( "log" "os" "github.com/moby/term" ) func main() { fd := os.Stdin.Fd() if term.IsTerminal(fd) { ws, err := term.GetWinsize(fd) if err != nil { log.Fatalf("term.GetWinsize: %s", err) } log.Printf("%d:%d\n", ws.Height, ws.Width) } } ``` -------------------------------- ### Create and use a volume in a container Source: https://github.com/docker/cli/blob/master/docs/reference/commandline/volume_create.md Creates a volume named 'hello' and then runs a container using busybox, mounting the volume at '/world'. The command then lists the contents of '/world' inside the container. ```console docker run -d -v hello:/world busybox ls /world ``` -------------------------------- ### List installed plugins Source: https://github.com/docker/cli/blob/master/docs/extend/_index.md Checks the status of installed plugins, verifying if they are enabled. ```console $ docker plugin ls ID NAME DESCRIPTION ENABLED aede66158353 rclone:latest Rclone volume plugin for Docker true ``` -------------------------------- ### Example cURL Request Source: https://github.com/docker/cli/blob/master/vendor/github.com/gorilla/mux/README.md This is an example of how to make a request to the /foo endpoint using cURL. ```bash curl localhost:8080/foo -v ``` -------------------------------- ### Install Cobra CLI Generator Source: https://github.com/docker/cli/blob/master/vendor/github.com/spf13/cobra/README.md Install the cobra-cli tool to bootstrap Cobra applications and command files. ```bash go install github.com/spf13/cobra-cli@latest ``` -------------------------------- ### Example Plugin Configuration (config.json) Source: https://github.com/docker/cli/blob/master/docs/extend/_index.md Defines the metadata for a Docker plugin, including its description, entrypoint, network settings, interface types, and Linux capabilities. ```json { "description": "sshFS plugin for Docker", "documentation": "https://docs.docker.com/engine/extend/plugins/", "entrypoint": ["/docker-volume-sshfs"], "network": { "type": "host" }, "interface": { "types": ["docker.volumedriver/1.0"], "socket": "sshfs.sock" }, "linux": { "capabilities": ["CAP_SYS_ADMIN"] } } ``` -------------------------------- ### List installed plugins Source: https://github.com/docker/cli/blob/master/docs/reference/commandline/plugin_install.md Displays a list of all installed plugins, including their ID, name, description, and enabled status. ```console $ docker plugin ls ID NAME DESCRIPTION ENABLED 69553ca1d123 vieux/sshfs:latest sshFS plugin for Docker true ``` -------------------------------- ### Create a service with configs Source: https://github.com/docker/cli/blob/master/docs/reference/commandline/service_create.md Provide a service with access to configurations using the `--config` flag. You can specify the source config, target path, and file mode. User and group IDs can also be set. ```console $ docker service create --name=redis --config redis-conf redis:7.4.1 ``` ```console $ docker service create --name redis \ --config source=redis-conf,target=/etc/redis/redis.conf,mode=0400 redis:7.4.1 ``` -------------------------------- ### Example cURL Response Source: https://github.com/docker/cli/blob/master/vendor/github.com/gorilla/mux/README.md This is an example of the response received when requesting /foo using cURL, showing the CORS headers. ```bash * Trying ::1... * TCP_NODELAY set * Connected to localhost (::1) port 8080 (#0) > GET /foo HTTP/1.1 > Host: localhost:8080 > User-Agent: curl/7.59.0 > Accept: */* > < HTTP/1.1 200 OK < Access-Control-Allow-Methods: GET,PUT,PATCH,OPTIONS < Access-Control-Allow-Origin: * < Date: Fri, 28 Jun 2019 20:13:30 GMT < Content-Length: 3 < Content-Type: text/plain; charset=utf-8 < * Connection #0 to host localhost left intact foo ``` -------------------------------- ### Example: Allow Authorization Flow Source: https://github.com/docker/cli/blob/master/docs/extend/plugins_authorization.md Demonstrates a successful authorization flow where a Docker command is allowed after being processed by an authorization plugin. ```console $ docker pull centos <...> f1b10cd84249: Pull complete <...> ``` -------------------------------- ### Example JSON output of service inspect Source: https://github.com/docker/cli/blob/master/docs/reference/commandline/service_inspect.md This is an example of the detailed JSON output produced when inspecting a Docker service. ```json [ { "ID": "dmu1ept4cxcfe8k8lhtux3ro3", "Version": { "Index": 12 }, "CreatedAt": "2016-06-17T18:44:02.558012087Z", "UpdatedAt": "2016-06-17T18:44:02.558012087Z", "Spec": { "Name": "redis", "TaskTemplate": { "ContainerSpec": { "Image": "redis:7.4.1" }, "Resources": { "Limits": {}, "Reservations": {} }, "RestartPolicy": { "Condition": "any", "MaxAttempts": 0 }, "Placement": {} }, "Mode": { "Replicated": { "Replicas": 1 } }, "UpdateConfig": {}, "EndpointSpec": { "Mode": "vip" } }, "Endpoint": { "Spec": {} } } ] ``` -------------------------------- ### Sample Docker config.json Source: https://github.com/docker/cli/blob/master/man/docker-config-json.5.md A sample config.json file demonstrating the structure and common properties like HttpHeaders, psFormat, imagesFormat, and detachKeys. ```json { "HttpHeaders": { "MyHeader": "MyValue" }, "psFormat": "table {{.ID}}\t{{.Image}}\t{{.Command}}\t{{.Labels}}", "imagesFormat": "table {{.ID}}\t{{.Repository}}\t{{.Tag}}\t{{.CreatedAt}}", "detachKeys": "ctrl-e,e" } ``` -------------------------------- ### Capabilities Response Example Source: https://github.com/docker/cli/blob/master/docs/extend/plugins_logging.md Example JSON response for the /LogDriver.Capabilities endpoint, indicating that the driver supports reading logs. ```json { "ReadLogs": true } ``` -------------------------------- ### Bind Mount Example with File Modification Source: https://github.com/docker/cli/blob/master/docs/reference/run.md Demonstrates a read-write bind mount where changes made inside the container are reflected on the host filesystem. ```console docker run -it --mount type=bind,source=.,target=/foo busybox / # echo "hello from container" > /foo/hello.txt / # exit $ cat hello.txt hello from container ``` -------------------------------- ### Start and attach to a container without interactive TTY Source: https://github.com/docker/cli/blob/master/docs/reference/commandline/container_attach.md Starts an Alpine container running `top` in detached mode and then attaches to it. Since the container was not started with `-i` and `-t`, CTRL-c terminates the container, and the default detach sequence CTRL-p CTRL-q has no effect. ```console $ docker run -d --name topdemo alpine top -b $ docker attach topdemo Mem: 2395856K used, 5638884K free, 2328K shrd, 61904K buff, 1524264K cached CPU: 0% usr 0% sys 0% nic 99% idle 0% io 0% irq 0% sirq Load average: 0.15 0.06 0.01 1/567 6 PID PPID USER STAT VSZ %VSZ CPU %CPU COMMAND 1 0 root R 1700 0% 3 0% top -b ``` ```console <...> PID PPID USER STAT VSZ %VSZ CPU %CPU COMMAND 1 0 root R 1700 0% 7 0% top -b ^P^Q ^C $ docker ps -a --filter name=topdemo CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 96254a235bd6 alpine "top -b" 44 seconds ago Exited (130) 8 seconds ago topdemo ``` -------------------------------- ### Commit a container with new CMD and EXPOSE instructions Source: https://github.com/docker/cli/blob/master/docs/reference/commandline/container_commit.md This example demonstrates committing a container and applying new `CMD` and `EXPOSE` Dockerfile instructions using the `--change` option. It then runs a container from the new image to verify the `CMD` instruction and checks the exposed ports. ```console $ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES c3f279d17e0a ubuntu:24.04 /bin/bash 7 days ago Up 25 hours desperate_dubinsky 197387f1b436 ubuntu:24.04 /bin/bash 7 days ago Up 25 hours focused_hamilton $ docker commit --change='CMD ["apachectl", "-DFOREGROUND"]' -c "EXPOSE 80" c3f279d17e0a svendowideit/testimage:version4 f5283438590d $ docker run -d svendowideit/testimage:version4 89373736e2e7f00bc149bd783073ac43d0507da250e999f3f1036e0db60817c0 $ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 89373736e2e7 testimage:version4 "apachectl -DFOREGROU" 3 seconds ago Up 2 seconds 80/tcp distracted_fermat c3f279d17e0a ubuntu:24.04 /bin/bash 7 days ago Up 25 hours desperate_dubinsky 197387f1b436 ubuntu:24.04 /bin/bash 7 days ago Up 25 hours focused_hamilton ``` -------------------------------- ### Sanitize Untrusted Content Example Source: https://github.com/docker/cli/blob/master/vendor/github.com/russross/blackfriday/v2/README.md To protect against JavaScript injection in untrusted content, refer to this example for proper sanitization techniques. ```go package main import ( "github.com/microcosm-cc/bluemonday" ) func main() { // Example usage for sanitizing untrusted content // See https://github.com/russross/blackfriday#sanitize-untrusted-content } ``` -------------------------------- ### Get opentelemetry-go with go get Source: https://github.com/docker/cli/blob/master/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md This command fetches the opentelemetry-go project into your Go workspace. Ignore any build constraint warnings. ```sh go get -d go.opentelemetry.io/otel ``` -------------------------------- ### List installed plugins Source: https://github.com/docker/cli/blob/master/docs/reference/commandline/plugin_disable.md Before disabling a plugin, you can list all installed plugins to verify their status. This helps confirm if the plugin is currently enabled. ```console docker plugin ls ```