Skip to content

Make Docker connection use Docker Desktop socket if available #520

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 19 additions & 12 deletions envs/docker.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ import (
"bytes"
"context"
"fmt"
"net"
"net/url"
"os"
"path/filepath"
Expand Down Expand Up @@ -69,17 +68,7 @@ func (l *Local) RelationshipsFromDocker() Relationships {
return nil
}

opts := [](docker.Opt){docker.FromEnv}
if host := os.Getenv(docker.EnvOverrideHost); host != "" && !strings.HasPrefix(host, "unix://") {
// Setting a dialer on top of a unix socket breaks the connection
// as the client then tries to connect to http:///path/to/socket and
// thus tries to resolve the /path/to/socket host
dialer := &net.Dialer{
Timeout: 2 * time.Second,
}
opts = append(opts, docker.WithDialContext(dialer.DialContext))
}
client, err := docker.NewClientWithOpts(opts...)
client, err := docker.NewClientWithOpts(docker.WithTimeout(2*time.Second), docker.FromEnv, dockerUseDesktopSocketIfAvailable)
if err != nil {
if l.Debug {
fmt.Fprintf(os.Stderr, "ERROR: %s\n", err)
Expand Down Expand Up @@ -473,6 +462,24 @@ func formatDockerPort(port uint16) string {
return strconv.FormatInt(int64(port), 10)
}

func dockerUseDesktopSocketIfAvailable(c *docker.Client) error {
if c.DaemonHost() != docker.DefaultDockerHost {
return nil
}

homeDir, err := os.UserHomeDir()
if err != nil {
return err
}

socketPath := filepath.Join(homeDir, ".docker/run/docker.sock")
if _, err := os.Stat(socketPath); err != nil {
return nil
}

return docker.WithHost(`unix://` + socketPath)(c)
}

func getEnvValue(env string, key string) string {
if len(key) == len(env) {
return ""
Expand Down