Skip to content

Commit

Permalink
cmd/atlas: support DOCKER_HOST for docker driver (#3249)
Browse files Browse the repository at this point in the history
  • Loading branch information
giautm authored Dec 10, 2024
1 parent 49d2479 commit 0bee868
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
18 changes: 14 additions & 4 deletions cmd/atlas/internal/docker/docker.go
Original file line number Diff line number Diff line change
Expand Up @@ -430,15 +430,25 @@ func (c *Container) Wait(ctx context.Context, timeout time.Duration) error {

// URL returns a URL to connect to the Container.
func (c *Container) URL() (*url.URL, error) {
host := "localhost"
// Check if the DOCKER_HOST env var is set.
// If it is, use the host from the URL.
if h := os.Getenv("DOCKER_HOST"); h != "" {
u, err := url.Parse(h)
if err != nil {
return nil, err
}
host = u.Hostname()
}
switch c.cfg.driver {
case DriverClickHouse:
return url.Parse(fmt.Sprintf("clickhouse://:%s@%s:%s/%s", c.Passphrase, "localhost", c.Port, c.cfg.Database))
return url.Parse(fmt.Sprintf("clickhouse://:%s@%s:%s/%s", c.Passphrase, host, c.Port, c.cfg.Database))
case DriverSQLServer:
return url.Parse(fmt.Sprintf("sqlserver://sa:%s@localhost:%s?database=%s", passSQLServer, c.Port, c.cfg.Database))
return url.Parse(fmt.Sprintf("sqlserver://sa:%s@%s:%s?database=%s", passSQLServer, host, c.Port, c.cfg.Database))
case DriverPostgres:
return url.Parse(fmt.Sprintf("postgres://postgres:%s@localhost:%s/%s?sslmode=disable", c.Passphrase, c.Port, c.cfg.Database))
return url.Parse(fmt.Sprintf("postgres://postgres:%s@%s:%s/%s?sslmode=disable", c.Passphrase, host, c.Port, c.cfg.Database))
case DriverMySQL, DriverMariaDB:
return url.Parse(fmt.Sprintf("%s://root:%s@localhost:%s/%s", c.cfg.driver, c.Passphrase, c.Port, c.cfg.Database))
return url.Parse(fmt.Sprintf("%s://root:%s@%s:%s/%s", c.cfg.driver, c.Passphrase, host, c.Port, c.cfg.Database))
default:
return nil, fmt.Errorf("unknown driver: %q", c.cfg.driver)
}
Expand Down
13 changes: 13 additions & 0 deletions cmd/atlas/internal/docker/docker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -414,3 +414,16 @@ func TestImageURL(t *testing.T) {
require.Equal(t, u, got.String())
}
}

func TestContainerURL(t *testing.T) {
c := &Container{cfg: Config{driver: "postgres"}, Passphrase: "pass", Port: "5432"}
u, err := c.URL()
require.NoError(t, err)
require.Equal(t, "postgres://postgres:pass@localhost:5432/?sslmode=disable", u.String())

// With DOCKER_HOST
t.Setenv("DOCKER_HOST", "tcp://host.docker.internal:2375")
u, err = c.URL()
require.NoError(t, err)
require.Equal(t, "postgres://postgres:[email protected]:5432/?sslmode=disable", u.String())
}

0 comments on commit 0bee868

Please sign in to comment.