Fix Docker API compatibility with network alias (#17167)

* Add BaseHostsFile to container configuration
* Do not copy /etc/hosts file from host when creating a container using Docker API

Signed-off-by: Gavin Lam <gavin.oss@tutamail.com>
This commit is contained in:
Gavin Lam
2023-12-11 23:25:51 -05:00
parent 077b000996
commit db68764d8b
13 changed files with 93 additions and 2 deletions

View File

@ -291,6 +291,12 @@ type ContainerNetworkConfig struct {
// bind-mounted inside the container.
// Conflicts with HostAdd.
UseImageHosts bool
// BaseHostsFile is the path to a hosts file, the entries from this file
// are added to the containers hosts file. As special value "image" is
// allowed which uses the /etc/hosts file from within the image and "none"
// which uses no base file at all. If it is empty we should default
// to the base_hosts_file configuration in containers.conf.
BaseHostsFile string `json:"baseHostsFile,omitempty"`
// Hosts to add in container
// Will be appended to host's host file
HostAdd []string `json:"hostsAdd,omitempty"`

View File

@ -2267,7 +2267,14 @@ func (c *Container) addHosts() error {
if err != nil {
return fmt.Errorf("failed to get container ip host entries: %w", err)
}
baseHostFile, err := etchosts.GetBaseHostFile(c.runtime.config.Containers.BaseHostsFile, c.state.Mountpoint)
// Consider container level BaseHostsFile configuration first.
// If it is empty, fallback to containers.conf level configuration.
baseHostsFileConf := c.config.BaseHostsFile
if baseHostsFileConf == "" {
baseHostsFileConf = c.runtime.config.Containers.BaseHostsFile
}
baseHostFile, err := etchosts.GetBaseHostFile(baseHostsFileConf, c.state.Mountpoint)
if err != nil {
return err
}

View File

@ -2373,6 +2373,19 @@ func WithGroupEntry(groupEntry string) CtrCreateOption {
}
}
// WithBaseHostsFile sets the option to copy /etc/hosts file.
func WithBaseHostsFile(baseHostsFile string) CtrCreateOption {
return func(ctr *Container) error {
if ctr.valid {
return define.ErrCtrFinalized
}
ctr.config.BaseHostsFile = baseHostsFile
return nil
}
}
// WithMountAllDevices sets the option to mount all of a privileged container's
// host devices
func WithMountAllDevices() CtrCreateOption {