Documentation
¶
Overview ¶
Package iotmakerdocker (English): Project by Helmut Kemper The idea behind this project is to facilitate the use of the moby project https://github.com/moby/moby
Package iotmakerdocker (Português): Projeto criado por Helmut Kemper A ideia desse projeto é facilitar a utilização do projeto moby https://github.com/moby/moby
Index ¶
- Constants
- func ContainerGetLasNameElement(name string) string
- func NewImagePullStatusChannel() (chanPointer *chan ContainerPullStatusSendToChannel)
- func NewPullStatusMonitor() (pullStatusChannel *chan ContainerPullStatusSendToChannel)
- func NewVolumeMount(list []Mount) (mountVolumesList []mount.Mount, err error)
- func TerminalToHtml(terminalString string) (htmlString string)
- type Consistency
- type ContainerInspect
- type ContainerInspectHost
- type ContainerInspectState
- type ContainerInspectVolumes
- type ContainerNetwork
- type ContainerNetworkData
- type ContainerNetworkDataList
- func (el ContainerNetworkDataList) GetEndpointIdByNetworkName(networkName string) (endpointID string)
- func (el ContainerNetworkDataList) GetGatewayByNetworkName(networkName string) (gateway string)
- func (el ContainerNetworkDataList) GetIpAddressByNetworkName(networkName string) (ipAddress string)
- func (el ContainerNetworkDataList) GetMacAddressByNetworkName(networkName string) (macAddress string)
- func (el ContainerNetworkDataList) GetNetworkIdByNetworkName(networkName string) (networkID string)
- type ContainerPullProgress
- type ContainerPullProgressDetail
- type ContainerPullStatus
- type ContainerPullStatusSendToChannel
- type ContainerPullStatusSendToChannelCount
- type DockerSystem
- func (el DockerSystem) AdjustImageName(imageName string) (name string)
- func (el *DockerSystem) ClientCreate() (err error)
- func (el *DockerSystem) ContainerCopyFrom(containerID string, sourcePath string) (reader io.ReadCloser, stats types.ContainerPathStat, err error)
- func (el *DockerSystem) ContainerCopyTo(containerID string, destinationPath string, content io.Reader) (err error)
- func (el *DockerSystem) ContainerCreate(imageName, containerName string, restartPolicy RestartPolicy, ...) (containerID string, err error)
- func (el *DockerSystem) ContainerCreateAndExposePortsAutomatically(imageName, containerName string, restartPolicy RestartPolicy, ...) (containerID string, err error)
- func (el *DockerSystem) ContainerCreateAndStart(imageName string, containerName string, restart RestartPolicy, ...) (containerID string, err error)
- func (el *DockerSystem) ContainerCreateExposePortsAutomaticallyAndStart(imageName, containerName string, restartPolicy RestartPolicy, ...) (containerID string, err error)
- func (el *DockerSystem) ContainerCreateWithConfig(configuration *container.Config, containerName string, ...) (containerID string, warnings []string, err error)
- func (el *DockerSystem) ContainerExecCommand(id string, commands []string) (exitCode int, running bool, stdOutput []byte, stdError []byte, err error)
- func (el *DockerSystem) ContainerFindIdByName(name string) (ID string, err error)
- func (el *DockerSystem) ContainerFindIdByNameContains(containsName string) (list []NameAndId, err error)
- func (el *DockerSystem) ContainerInspect(id string) (inspect types.ContainerJSON, err error)
- func (el *DockerSystem) ContainerInspectByName(name string) (inspect types.ContainerJSON, err error)
- func (el *DockerSystem) ContainerInspectByNameContains(searchTerm string) (list []types.ContainerJSON, err error)
- func (el *DockerSystem) ContainerInspectJSon(id string) (inspect []byte, err error)
- func (el *DockerSystem) ContainerInspectJSonByName(name string) (inspect []byte, err error)
- func (el *DockerSystem) ContainerInspectParsed(id string) (parsed ContainerInspect, err error)
- func (el *DockerSystem) ContainerListAll() (list []types.Container, err error)
- func (el *DockerSystem) ContainerListWithOptions(quiet bool, size bool, all bool, latest bool, since string, before string, ...) (list []types.Container, err error)
- func (el *DockerSystem) ContainerLogs(id string) (log []byte, err error)
- func (el *DockerSystem) ContainerLogsWaitText(id string, text string, out io.Writer) (logContainer []byte, err error)
- func (el *DockerSystem) ContainerLogsWaitTextWithTimeout(id string, text string, timeout time.Duration, out io.Writer) (logContainer []byte, err error)
- func (el *DockerSystem) ContainerNetworkInspect(id string) (netDataList ContainerNetworkDataList, err error)
- func (el *DockerSystem) ContainerPause(id string) (err error)
- func (el *DockerSystem) ContainerRemove(id string, removeVolumes, removeLinks, force bool) (err error)
- func (el *DockerSystem) ContainerRestart(id string) (err error)
- func (el *DockerSystem) ContainerRestartWithTimeout(id string, timeout time.Duration) (err error)
- func (el *DockerSystem) ContainerStart(id string) (err error)
- func (el *DockerSystem) ContainerStatisticsOneShot(id string) (statsRet types.Stats, err error)
- func (el *DockerSystem) ContainerStatisticsOneShotByName(name string) (ret types.Stats, err error)
- func (el *DockerSystem) ContainerStop(id string) (err error)
- func (el *DockerSystem) ContainerStopAndRemove(id string) (err error)
- func (el *DockerSystem) ContainerUnpause(id string) (err error)
- func (el *DockerSystem) ContainerWaitStatusNextExit(id string) (err error)
- func (el *DockerSystem) ContainerWaitStatusNotRunning(id string, timeout time.Duration) (err error)
- func (el *DockerSystem) ContainerWaitStatusRemoved(id string) (err error)
- func (el *DockerSystem) ContextCreate()
- func (el *DockerSystem) DockerInfo() (info types.Info, err error)
- func (el *DockerSystem) FileMakeAbsolutePath(filePath string) (fileAbsolutePath string, err error)
- func (el *DockerSystem) FindDockerFile(folderPath string) (fullPathInsideTarFile string, err error)
- func (el DockerSystem) GetConfig() (config *container.Config)
- func (el *DockerSystem) ImageBuild(dockerFileTarReader io.Reader, imageBuildOptions types.ImageBuildOptions) (reader io.ReadCloser, err error)
- func (el *DockerSystem) ImageBuildFromFolder(folderPath string, imageName string, tags []string, ...) (imageID string, err error)
- func (el *DockerSystem) ImageBuildFromRemoteServer(server, imageName string, tags []string, ...) (imageID string, err error)
- func (el DockerSystem) ImageBuildPrepareFolderContext(dirPath string) (file *bytes.Reader, err error)
- func (el DockerSystem) ImageBuildPrepareFolderContextSupport(dirPath, toRemoveInsideTarFilePathList string, buf *bytes.Buffer, ...) (err error)
- func (el *DockerSystem) ImageFindIdByName(name string) (ID string, err error)
- func (el *DockerSystem) ImageFindIdByNameContains(name string) (list []NameAndId, err error)
- func (el *DockerSystem) ImageGarbageCollector() (err error)
- func (el *DockerSystem) ImageInspect(id string) (inspect types.ImageInspect, err error)
- func (el *DockerSystem) ImageList() (list []types.ImageSummary, err error)
- func (el *DockerSystem) ImageListExposedNatPort(imageId string) (nat.PortMap, error)
- func (el *DockerSystem) ImageListExposedPorts(id string) (portList []nat.Port, err error)
- func (el *DockerSystem) ImageListExposedPortsByName(name string) (portList []nat.Port, err error)
- func (el *DockerSystem) ImageListExposedVolumes(id string) (list []string, err error)
- func (el *DockerSystem) ImageListExposedVolumesByName(name string) (list []string, err error)
- func (el *DockerSystem) ImageMountNatPortListChangeExposed(imageId string, currentPortList, changeToPortList []nat.Port) (nat.PortMap, error)
- func (el *DockerSystem) ImageMountNatPortListChangeExposedWithIpAddress(imageId, ipAddress string, currentPortList, changeToPortList []nat.Port) (nat.PortMap, error)
- func (el *DockerSystem) ImagePull(name string, channel chan ContainerPullStatusSendToChannel) (imageId string, imageName string, err error)
- func (el *DockerSystem) ImageRemove(id string, force, pruneChildren bool) (err error)
- func (el *DockerSystem) ImageRemoveByName(name string, force, pruneChildren bool) (err error)
- func (el *DockerSystem) ImageVerifyVolume(id, path string) (bool, error)
- func (el *DockerSystem) Init() (err error)
- func (el *DockerSystem) NetworkConnect(networkID, containerID string, config *network.EndpointSettings) (err error)
- func (el *DockerSystem) NetworkCreate(name string, drive NetworkDrive, scope, subnet, gateway string) (id string, networkGenerator *NextNetworkAutoConfiguration, err error)
- func (el *DockerSystem) NetworkDisconnect(networkID, containerID string, force bool) (err error)
- func (el *DockerSystem) NetworkFindIdByName(name string) (id string, err error)
- func (el *DockerSystem) NetworkFindIdByNameContains(name string) (list []NameAndId, err error)
- func (el *DockerSystem) NetworkFindNetworkTypeBridgePublic() (inspect types.NetworkResource, err error)
- func (el *DockerSystem) NetworkGetGenerator(name string) (configuration *NextNetworkAutoConfiguration)
- func (el *DockerSystem) NetworkInspect(id string) (inspect types.NetworkResource, err error)
- func (el *DockerSystem) NetworkList() (netList []types.NetworkResource, err error)
- func (el *DockerSystem) NetworkListLocalCreated() (list map[string]string)
- func (el *DockerSystem) NetworkRemove(id string) (err error)
- func (el *DockerSystem) NetworkRemoveByName(name string) (err error)
- func (el *DockerSystem) NetworkVerifyName(name string) (exists bool, err error)
- func (el DockerSystem) RemoveAllByNameContains(name string) (err error)
- func (el *DockerSystem) SetHealthcheck(healthcheck HealthConfig)
- func (el *DockerSystem) SetOnBuild(onBuild []string)
- func (el *DockerSystem) VolumeCreate(labels map[string]string, name string) (volume types.Volume, err error)
- func (el *DockerSystem) VolumeFindByName(name string) (volume types.Volume, err error)
- func (el *DockerSystem) VolumeInspect(ID string) (inspect types.Volume, err error)
- func (el *DockerSystem) VolumeList() (volList []types.Volume, err error)
- func (el *DockerSystem) VolumeRemove(name string) (err error)
- func (el DockerSystem) VolumesUnreferencedRemove() (err error)
- type EndpointIPAMConfig
- type EndpointSettings
- type ExecResult
- type HealthConfig
- type IPv4Generator
- func (el *IPv4Generator) GetCurrentIP() (digitA, digitB, digitC, digitD byte)
- func (el *IPv4Generator) GetCurrentIPAsString() (ip string)
- func (el *IPv4Generator) IncCurrentIP() (err error)
- func (el *IPv4Generator) Init(...) (err error)
- func (el *IPv4Generator) InitWithString(gateway string, subnet string) (err error)
- func (el IPv4Generator) String() (currentIP string)
- type InspectVolumeMount
- type Mount
- type NameAndId
- type NetworkDrive
- type NextNetworkAutoConfiguration
- type RestartPolicy
- type TerminalColor
- type Type
- type VolumeMountType
Examples ¶
- ContainerGetLasNameElement
- DockerSystem.AdjustImageName
- DockerSystem.ContainerCreate
- DockerSystem.ContainerCreateAndExposePortsAutomatically
- DockerSystem.ContainerCreateAndStart
- DockerSystem.ContainerCreateExposePortsAutomaticallyAndStart
- DockerSystem.ContainerExecCommand
- DockerSystem.ContainerFindIdByName
- DockerSystem.ContainerFindIdByNameContains
- DockerSystem.ContainerInspect
- DockerSystem.ContainerInspectByName
- DockerSystem.ContainerInspectByNameContains
- DockerSystem.ContainerInspectJSon
- DockerSystem.ContainerInspectJSonByName
- DockerSystem.ContainerListAll
- DockerSystem.ContainerListWithOptions
- DockerSystem.ContainerLogs
- DockerSystem.ContainerLogsWaitText
- DockerSystem.ContainerLogsWaitTextWithTimeout
- DockerSystem.ContainerNetworkInspect
- DockerSystem.ContainerPause
- DockerSystem.ContainerRemove
- DockerSystem.ContainerStart
- DockerSystem.ContainerStatisticsOneShot
- DockerSystem.ContainerStatisticsOneShotByName
- DockerSystem.ContainerStop
- DockerSystem.ContainerStopAndRemove
- DockerSystem.ContainerWaitStatusNextExit
- DockerSystem.ContainerWaitStatusNotRunning
- DockerSystem.ContainerWaitStatusRemoved
- DockerSystem.ImageBuildFromFolder
- DockerSystem.ImageFindIdByName
- DockerSystem.ImageFindIdByNameContains
- DockerSystem.ImageGarbageCollector
- DockerSystem.ImageList
- DockerSystem.ImageListExposedNatPort
- DockerSystem.ImageListExposedPorts
- DockerSystem.ImageListExposedPortsByName
- DockerSystem.ImageListExposedVolumes
- DockerSystem.ImageListExposedVolumesByName
- DockerSystem.ImagePull
- DockerSystem.ImageRemove
- DockerSystem.ImageRemoveByName
- DockerSystem.NetworkConnect
- DockerSystem.NetworkCreate
- DockerSystem.NetworkDisconnect
- DockerSystem.NetworkFindIdByName
- DockerSystem.NetworkFindIdByNameContains
- DockerSystem.NetworkInspect
- DockerSystem.NetworkList
- DockerSystem.NetworkRemove
- DockerSystem.NetworkRemoveByName
- DockerSystem.NetworkVerifyName
- DockerSystem.RemoveAllByNameContains
- DockerSystem.VolumeFindByName
- DockerSystem.VolumeList
- DockerSystem.VolumeRemove
Constants ¶
const ( KAnsiReset = `\u001b[0m` KAnsiBold = `\u001b[1m` KAnsiUnderline = `\u001b[4m` KAnsiReversed = `\u001b[7m` KAnsiBlack = `\u001b[30m` KAnsiRed = `\u001b[31m` KAnsiGreen = `\u001b[32m` KAnsiYellow = `\u001b[33m` KAnsiBlue = `\u001b[34m` KAnsiPurple = `\u001b[35m` KAnsiCyan = `\u001b[36m` KAnsiWhite = `\u001b[37m` KAnsiBrightBlack = `\u001b[90m` KAnsiBrightRed = `\u001b[91m` KAnsiBrightGreen = `\u001b[92m` KAnsiBrightYellow = `\u001b[93m` KAnsiBrightBlue = `\u001b[94m` KAnsiBrightPurple = `\u001b[95m` KAnsiBrightCyan = `\u001b[96m` KAnsiBrightWhite = `\u001b[97m` KAnsiBgBlack = `\u001b[40m` KAnsiBgRed = `\u001b[41m` KAnsiBgGreen = `\u001b[42m` KAnsiBgYellow = `\u001b[43m` KAnsiBgBlue = `\u001b[44m` KAnsiBgPurple = `\u001b[45m` KAnsiBgCyan = `\u001b[46m` KAnsiBgWhite = `\u001b[47m` KAnsiBrightBgBlack = `\u001b[100m` KAnsiBrightBgRed = `\u001b[101m` KAnsiBrightBgGreen = `\u001b[102m` KAnsiBrightBgYellow = `\u001b[103m` KAnsiBrightBgBlue = `\u001b[104m` KAnsiBrightBgPurple = `\u001b[105m` KAnsiBrightBgCyan = `\u001b[106m` KAnsiBrightBgWhite = `\u001b[107m` )
const ( // KVolumeMountTypeBindString TypeBind is the type for mounting host dir (real folder inside computer where this code work) KVolumeMountTypeBindString = "bind" // KVolumeMountTypeVolumeString TypeVolume is the type for remote storage volumes KVolumeMountTypeVolumeString = "volume" // KVolumeMountTypeTmpfsString TypeTmpfs is the type for mounting tmpfs KVolumeMountTypeTmpfsString = "tmpfs" // KVolumeMountTypeNpipeString TypeNamedPipe TypeNamedPipe is the type for mounting Windows named pipes KVolumeMountTypeNpipeString = "npipe" )
Variables ¶
This section is empty.
Functions ¶
func ContainerGetLasNameElement ¶
ContainerGetLasNameElement (English): Eliminates the slash '/' in the name of some containers
ContainerGetLasNameElement (Português): Elimina a barra '/' do nome de alguns containers
Example ¶
name := "/container_mongo" fmt.Printf("%v\n", ContainerGetLasNameElement(name)) name = "db/container_mongo" fmt.Printf("%v\n", ContainerGetLasNameElement(name))
Output: container_mongo db/container_mongo
func NewImagePullStatusChannel ¶
func NewImagePullStatusChannel() ( chanPointer *chan ContainerPullStatusSendToChannel, )
NewImagePullStatusChannel (English): Prepare a new channel for pull/build data
NewImagePullStatusChannel (Português): Prepara um canal para os dados de pull/build
func NewPullStatusMonitor ¶
func NewPullStatusMonitor() (pullStatusChannel *chan ContainerPullStatusSendToChannel)
NewPullStatusMonitor (English): Small example how to use channel do monitoring image/container build
NewPullStatusMonitor (Português): Pequeno exemplo de como usar o canal para ver imagem/container sendo criados
func NewVolumeMount ¶
func TerminalToHtml ¶
Types ¶
type Consistency ¶
type Consistency string
type ContainerInspect ¶
type ContainerInspect struct { ID string Name string Created time.Time Args []string ImageId string RestartCount int Volumes ContainerInspectVolumes State ContainerInspectState Host ContainerInspectHost Network ContainerNetwork }
type ContainerInspectHost ¶
type ContainerInspectHost struct { NetworkMode string Binds []string IsDefault bool IsHost bool IsContainer bool IsPrivate bool IsNone bool IsBridge bool IsUserDefined bool UserDefined string PortBindings nat.PortMap PortRestartPolicyName string PortRestartPolicyMaximumRetryCount int ExposedPorts nat.PortSet }
type ContainerInspectState ¶
type ContainerInspectVolumes ¶
type ContainerInspectVolumes struct { VolumeDriver string VolumesFrom []string Mounts []InspectVolumeMount }
type ContainerNetwork ¶
type ContainerNetworkData ¶
type ContainerNetworkDataList ¶
type ContainerNetworkDataList map[string]ContainerNetworkData
func (ContainerNetworkDataList) GetEndpointIdByNetworkName ¶
func (el ContainerNetworkDataList) GetEndpointIdByNetworkName(networkName string) (endpointID string)
func (ContainerNetworkDataList) GetGatewayByNetworkName ¶
func (el ContainerNetworkDataList) GetGatewayByNetworkName(networkName string) (gateway string)
func (ContainerNetworkDataList) GetIpAddressByNetworkName ¶
func (el ContainerNetworkDataList) GetIpAddressByNetworkName(networkName string) (ipAddress string)
func (ContainerNetworkDataList) GetMacAddressByNetworkName ¶
func (el ContainerNetworkDataList) GetMacAddressByNetworkName(networkName string) (macAddress string)
func (ContainerNetworkDataList) GetNetworkIdByNetworkName ¶
func (el ContainerNetworkDataList) GetNetworkIdByNetworkName(networkName string) (networkID string)
type ContainerPullProgress ¶
type ContainerPullProgress struct { Stream string `json:"stream"` Status string `json:"status"` ProgressDetail ContainerPullProgressDetail `json:"progressDetail"` ID string `json:"id"` SysStatus ContainerPullStatus `json:"-"` ImageName string SuccessfullyBuildContainer bool SuccessfullyBuildImage bool }
type ContainerPullStatus ¶
type ContainerPullStatus int
const ( KContainerPullStatusWaiting ContainerPullStatus = iota + 1 KContainerPullStatusDownloading KContainerPullStatusVerifyingChecksum KContainerPullStatusDownloadComplete KContainerPullStatusExtracting KContainerPullStatusPullComplete KContainerPullStatusBuilding KContainerPullStatusComplete )
type ContainerPullStatusSendToChannel ¶
type ContainerPullStatusSendToChannel struct { Waiting int Downloading ContainerPullStatusSendToChannelCount VerifyingChecksum int DownloadComplete int Extracting ContainerPullStatusSendToChannelCount PullComplete int ImageName string ImageID string ContainerID string Closed bool Stream string SuccessfullyBuildContainer bool SuccessfullyBuildImage bool IdAuxiliaryImages []string }
func (*ContainerPullStatusSendToChannel) SetAuxiliaryImageList ¶
func (el *ContainerPullStatusSendToChannel) SetAuxiliaryImageList(list []string)
type DockerSystem ¶
type DockerSystem struct { ContainerName string Config *container.Config // contains filtered or unexported fields }
func NewClient ¶
func NewClient() ( dockerSystem *DockerSystem, err error, )
NewClient (English): Prepare docker system
Example: err, dockerSys := factoryDocker.NewClient() if err != nil { panic(err) } dockerSys.ContainerCreateChangeExposedPortAndStart(...)
NewClient (Português): Prepara o docker
Exemplo: err, dockerSys := factoryDocker.NewClient() if err != nil { panic(err) } dockerSys.ContainerCreateChangeExposedPortAndStart(...)
func (DockerSystem) AdjustImageName ¶
func (el DockerSystem) AdjustImageName(imageName string) (name string)
AdjustImageName
Test and adjust image name to name+":"+version_string
Example ¶
var err error var dockerSys *DockerSystem var correctImageName string dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } correctImageName = dockerSys.AdjustImageName("alpine") fmt.Printf("%v\n", correctImageName) correctImageName = dockerSys.AdjustImageName("alpine:") fmt.Printf("%v\n", correctImageName)
Output: alpine:latest alpine:latest
func (*DockerSystem) ClientCreate ¶
func (el *DockerSystem) ClientCreate() ( err error, )
ClientCreate (English): Create a new client from docker
Example: dockerSys = &iotmakerDocker.DockerSystem{} dockerSys.ContextCreate() err := dockerSys.ClientCreate() if err != nil { panic(err) } dockerSys.ContainerCreateChangeExposedPortAndStart(...)
ClientCreate (Português): Cria um novo cliente para o docker
Exemplo: dockerSys = &iotmakerDocker.DockerSystem{} dockerSys.ContextCreate() err := dockerSys.ClientCreate() if err != nil { panic(err) } dockerSys.ContainerCreateChangeExposedPortAndStart(...)
func (*DockerSystem) ContainerCopyFrom ¶
func (el *DockerSystem) ContainerCopyFrom( containerID string, sourcePath string, ) ( reader io.ReadCloser, stats types.ContainerPathStat, err error, )
ContainerCopyFrom
Copy from container to host
func (*DockerSystem) ContainerCopyTo ¶
func (el *DockerSystem) ContainerCopyTo( containerID string, destinationPath string, content io.Reader, ) ( err error, )
ContainerCopyTo
Copy to host from container
func (*DockerSystem) ContainerCreate ¶
func (el *DockerSystem) ContainerCreate( imageName, containerName string, restartPolicy RestartPolicy, portExposedList nat.PortMap, mountVolumes []mount.Mount, containerNetwork *network.NetworkingConfig, ) ( containerID string, err error, )
ContainerCreate (English): Creates a container
imageName: image name for download and pull containerName: unique container name restartPolicy: KRestartPolicyNo - Do not automatically restart the container. KRestartPolicyOnFailure - Restart the container if it exits due to an error, which manifests as a non-zero exit code. KRestartPolicyAlways - Always restart the container if it stops. If it is manually stopped, it is restarted only when Docker daemon restarts or the container itself is manually restarted. (See the second bullet listed in restart policy details) KRestartPolicyUnlessStopped - Similar to always, except that when the container is stopped (manually or otherwise), it is not restarted even after Docker daemon restarts. portExposedList: nat.PortMap exposed port list from container key: string (container port umber/protocol tcp|udp). Example: "3000/tcp" value: []nat.PortBinding key: one key per server host port value: struct{ HostPort: numeric string host port }. Example: {HostPort: "3000"} mountVolumes: array of mount.Mount{} Type: KVolumeMountTypeBindString: Bind is the type for mounting host dir (real folder inside computer where this code work) KVolumeMountTypeVolumeString: Volume is the type for remote storage volumes KVolumeMountTypeTmpfsString: Tmpfs is the type for mounting tmpfs KVolumeMountTypeNpipeString: NPipe is the type for mounting Windows named pipes Source: path inside the host machine Target: path inside the container after container start Note: For a complete list of volumes exposed by image, use ImageListExposedVolumes(id) and ImageListExposedVolumesByName(name) containerNetwork: container network configuration Note: please, use NetworkCreate() for correct configuration of network
ContainerCreate (Português): Cria um container listas na imagem
imageName: nome da image para download e pull containerName: nome do container (deve ser único) restartPolicy: KRestartPolicyNo - Não reinicia o container automaticamente. KRestartPolicyOnFailure - Reinicia o container ser ele terminar por error, com o manifesto contendo um valore de erro diferente de zero. KRestartPolicyAlways - Sempre reinicia o container se ele parar. Caso o container seja parado, ele só reinicia se o Docker daemon reiniciar ou com reinício manual (Veja 'second bullet' nas políticas de reinício do container) KRestartPolicyUnlessStopped - Similar ao always, exceto quando o container é parado (manualmente ou não) e não é reiniciado, mesmo quando o Docker daemon reinicia portExposedList: nat.PortMap lista de portas expostas do container key: string (número da porta do container/protocolo tcp|udp). Exemplo: "3000/tcp" value: []nat.PortBinding key: uma chave por porta no servidor hospedeiro value: struct{ HostPort: string numérica da porta no servidor hospedeiro }. Example: {HostPort: "3000"} mountVolumes: array de mount.Mount{} Type: KVolumeMountTypeBindString: Vincula uma pasta do computador, host, com uma pasta do container KVolumeMountTypeVolumeString: Volume é usado para arquivos de armazenamento remoto KVolumeMountTypeTmpfsString: Tmpfs arquiva os dados em memória RAM de forma volátil KVolumeMountTypeNpipeString: NPipe é um tipo de volume do Windows chamado de pipes Source: caminho dentro do computador, host Target: caminho dentro do container quando ele inicia Nota: Para uma lista completa de volumes expostos na imagem, use ImageListExposedVolumes(id) e ImageListExposedVolumesByName(name) containerNetwork: configuração de rede do container Nota: Por favor, use NetworkCreate() para a forma correta da configuração de rede
Example ¶
var err error var containerId string var imageId string var networkId string var dockerSys *DockerSystem var networkAutoConfiguration *NextNetworkAutoConfiguration var networkNextAddress *network.NetworkingConfig // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê _todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: 'static' folder path // Português: caminho da pasta 'static' var smallServerPathStatic string smallServerPathStatic = smallServerPath + string(os.PathSeparator) + "static" // English: 'index.html' file path // Português: caminho do arquivo 'index.html' var smallServerPathStaticContent string smallServerPathStaticContent = smallServerPathStatic + string(os.PathSeparator) + "index.html" // English: create a new default client. // Português: cria um novo cliente com configurações padrão. dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: create a network named 'network_delete_before_test' // Português: cria uma nova rede de nome 'network_delete_before_test' networkId, networkAutoConfiguration, err = dockerSys.NetworkCreate( "network_delete_before_test", KNetworkDriveBridge, "local", "10.0.0.0/16", "10.0.0.1", ) if err != nil { panic(err) } if networkId == "" { err = errors.New("network id was not generated") panic(err) } // English: get next ip address from network, '10.0.0.2' // Português: pega o próxima endereço da rede, '10.0.0.2' _, networkNextAddress, err = networkAutoConfiguration.GetNext() if err != nil { panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: mount and start a container // Português: monta i inicializa o container containerId, err = dockerSys.ContainerCreate( // image name "image_server_delete_before_test:latest", // container name "container_delete_before_test", // restart policy KRestartPolicyUnlessStopped, // portMap nat.PortMap{ // container port number/protocol [tpc/udp] "3000/tcp": []nat.PortBinding{ // server original port { // server output port number HostPort: "9002", }, }, }, // mount volumes []mount.Mount{ { // bind - is the type for mounting host dir (real folder inside computer where // this code work) Type: KVolumeMountTypeBindString, // path inside host machine Source: smallServerPathStatic, // path inside image Target: "/static", }, }, // nil or container network configuration networkNextAddress, ) if err != nil { panic(err) } if containerId == "" { err = errors.New("container id was not generated") panic(err) } // English: container start // Português: inicia o container err = dockerSys.ContainerStart(containerId) if err != nil { panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true var page []byte var found int var response *http.Response // English: contents of the static server index.html page // Português: conteúdo da página index.html do servidor estático var htmlIndexContent1 = []byte("<!DOCTYPE html><html><body><p>I'm alive!</p></body></html>") err = ioutil.WriteFile(smallServerPathStaticContent, htmlIndexContent1, os.ModePerm) if err != nil { panic(err) } // English: takes the content from the server for testing // Português: pega o conteúdo do servidor para teste response, err = http.Get("http://localhost:9002") if err != nil { panic(err) } page, err = ioutil.ReadAll(response.Body) if err != nil { panic(err) } // English: compare content // Português: compara o conteúdo found = bytes.Compare(page, htmlIndexContent1) if found == 1 { err = errors.New("small server content error") panic(err) } // English: contents of the static server index.html page // Português: conteúdo da página index.html do servidor estático htmlIndexContent1 = []byte("<!DOCTYPE html><html><body><p>I'm alive Dr. Frankenstein!</p></body></html>") err = ioutil.WriteFile(smallServerPathStaticContent, htmlIndexContent1, os.ModePerm) if err != nil { panic(err) } // English: takes the content from the server for testing // Português: pega o conteúdo do servidor para teste response, err = http.Get("http://localhost:9002") if err != nil { panic(err) } page, err = ioutil.ReadAll(response.Body) if err != nil { panic(err) } // English: compare content // Português: compara o conteúdo found = bytes.Compare(page, htmlIndexContent1) if found == 1 { err = errors.New("small server content error") panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) ContainerCreateAndExposePortsAutomatically ¶
func (el *DockerSystem) ContainerCreateAndExposePortsAutomatically( imageName, containerName string, restartPolicy RestartPolicy, mountVolumes []mount.Mount, containerNetwork *network.NetworkingConfig, ) ( containerID string, err error, )
ContainerCreateAndExposePortsAutomatically (English): Creates a container and automatically exposes the ports listed in the image
imageName: image name for download and pull containerName: unique container name restartPolicy: KRestartPolicyNo - Do not automatically restart the container. KRestartPolicyOnFailure - Restart the container if it exits due to an error, which manifests as a non-zero exit code. KRestartPolicyAlways - Always restart the container if it stops. If it is manually stopped, it is restarted only when Docker daemon restarts or the container itself is manually restarted. (See the second bullet listed in restart policy details) KRestartPolicyUnlessStopped - Similar to always, except that when the container is stopped (manually or otherwise), it is not restarted even after Docker daemon restarts. mountVolumes: array of mount.Mount{} Type: KVolumeMountTypeBindString: Bind is the type for mounting host dir (real folder inside computer where this code work) KVolumeMountTypeVolumeString: Volume is the type for remote storage volumes KVolumeMountTypeTmpfsString: Tmpfs is the type for mounting tmpfs KVolumeMountTypeNpipeString: NPipe is the type for mounting Windows named pipes Source: path inside the host machine Target: path inside the container after container start Note: For a complete list of volumes exposed by image, use ImageListExposedVolumes(id) and ImageListExposedVolumesByName(name) containerNetwork: container network configuration Note: please, use NetworkCreate() for correct configuration of network
ContainerCreateAndExposePortsAutomatically (Português): Cria um container e automaticamente expões as portas listas na imagem
imageName: nome da image para download e pull containerName: nome do container (deve ser único) restartPolicy: KRestartPolicyNo - Não reinicia o container automaticamente. KRestartPolicyOnFailure - Reinicia o container ser ele terminar por error, com o manifesto contendo um valore de erro diferente de zero. KRestartPolicyAlways - Sempre reinicia o container se ele parar. Caso o container seja parado, ele só reinicia se o Docker daemon reiniciar ou com reinício manual (Veja 'second bullet' nas políticas de reinício do container) KRestartPolicyUnlessStopped - Similar ao always, exceto quando o container é parado (manualmente ou não) e não é reiniciado, mesmo quando o Docker daemon reinicia mountVolumes: array de mount.Mount{} Type: KVolumeMountTypeBindString: Vincula uma pasta do computador, host, com uma pasta do container KVolumeMountTypeVolumeString: Volume é usado para arquivos de armazenamento remoto KVolumeMountTypeTmpfsString: Tmpfs arquiva os dados em memória RAM de forma volátil KVolumeMountTypeNpipeString: NPipe é um tipo de volume do Windows chamado de pipes Source: caminho dentro do computador, host Target: caminho dentro do container quando ele inicia Nota: Para uma lista completa de volumes expostos na imagem, use ImageListExposedVolumes(id) e ImageListExposedVolumesByName(name) containerNetwork: configuração de rede do container Nota: Por favor, use NetworkCreate() para a forma correta da configuração de rede
Example ¶
var err error var containerId string var imageId string var networkId string var dockerSys *DockerSystem var networkAutoConfiguration *NextNetworkAutoConfiguration var networkNextAddress *network.NetworkingConfig // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: 'static' folder path // Português: caminho da pasta 'static' var smallServerPathStatic string smallServerPathStatic = smallServerPath + string(os.PathSeparator) + "static" // English: 'index.html' file path // Português: caminho do arquivo 'index.html' var smallServerPathStaticContent string smallServerPathStaticContent = smallServerPathStatic + string(os.PathSeparator) + "index.html" // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: create a network named 'network_delete_before_test' // Português: cria uma nova rede de nome 'network_delete_before_test' networkId, networkAutoConfiguration, err = dockerSys.NetworkCreate( "network_delete_before_test", KNetworkDriveBridge, "local", "10.0.0.0/16", "10.0.0.1", ) if err != nil { panic(err) } if networkId == "" { err = errors.New("network id was not generated") panic(err) } // English: get next ip address from network, '10.0.0.2' // Português: pega o próxima endereço da rede, '10.0.0.2' _, networkNextAddress, err = networkAutoConfiguration.GetNext() if err != nil { panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: mount and start a container // Português: monta i inicializa o container containerId, err = dockerSys.ContainerCreateAndExposePortsAutomatically( "image_server_delete_before_test:latest", // image name "container_delete_before_test", // container name KRestartPolicyUnlessStopped, // restart policy []mount.Mount{ // mount volumes { Type: KVolumeMountTypeBindString, // bind - is the type for mounting host dir // (real folder inside computer where this // code work) Source: smallServerPathStatic, // path inside host machine Target: "/static", // path inside image }, }, networkNextAddress, // [optional] container network ) if err != nil { panic(err) } if containerId == "" { err = errors.New("container id was not generated") panic(err) } // English: start a container by id // Português: inicia um container por id err = dockerSys.ContainerStart(containerId) if err != nil { panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true var page []byte var found int var response *http.Response // English: contents of the static server index.html page // Português: conteúdo da página index.html do servidor estático var htmlIndexContent1 = []byte("<!DOCTYPE html><html><body><p>I'm alive!</p></body></html>") err = ioutil.WriteFile(smallServerPathStaticContent, htmlIndexContent1, os.ModePerm) if err != nil { panic(err) } // English: takes the content from the server for testing // Português: pega o conteúdo do servidor para teste response, err = http.Get("http://localhost:3000") if err != nil { panic(err) } page, err = ioutil.ReadAll(response.Body) if err != nil { panic(err) } // English: compare content // Português: compara o conteúdo found = bytes.Compare(page, htmlIndexContent1) if found == 1 { err = errors.New("small server content error") panic(err) } // English: contents of the static server index.html page // Português: conteúdo da página index.html do servidor estático htmlIndexContent1 = []byte("<!DOCTYPE html><html><body><p>I'm alive Dr. Frankenstein!</p></body></html>") err = ioutil.WriteFile(smallServerPathStaticContent, htmlIndexContent1, os.ModePerm) if err != nil { panic(err) } // English: takes the content from the server for testing // Português: pega o conteúdo do servidor para teste response, err = http.Get("http://localhost:3000") if err != nil { panic(err) } page, err = ioutil.ReadAll(response.Body) if err != nil { panic(err) } // English: compare content // Português: compara o conteúdo found = bytes.Compare(page, htmlIndexContent1) if found == 1 { err = errors.New("small server content error") panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) ContainerCreateAndStart ¶
func (el *DockerSystem) ContainerCreateAndStart( imageName string, containerName string, restart RestartPolicy, portExposedList nat.PortMap, mountVolumes []mount.Mount, containerNetwork *network.NetworkingConfig, ) ( containerID string, err error, )
ContainerCreateAndStart (English): Creates a container, automatically exposes the ports listed in the image and start then
imageName: image name for download and pull containerName: unique container name restartPolicy: KRestartPolicyNo - Do not automatically restart the container. KRestartPolicyOnFailure - Restart the container if it exits due to an error, which manifests as a non-zero exit code. KRestartPolicyAlways - Always restart the container if it stops. If it is manually stopped, it is restarted only when Docker daemon restarts or the container itself is manually restarted. (See the second bullet listed in restart policy details) KRestartPolicyUnlessStopped - Similar to always, except that when the container is stopped (manually or otherwise), it is not restarted even after Docker daemon restarts. portExposedList: nat.PortMap exposed port list from container key: string (container port umber/protocol tcp|udp). Example: "3000/tcp" value: []nat.PortBinding key: one key per server host port value: struct{ HostPort: numeric string host port }. Example: {HostPort: "3000"} mountVolumes: array of mount.Mount{} Type: KVolumeMountTypeBindString: Bind is the type for mounting host dir (real folder inside computer where this code work) KVolumeMountTypeVolumeString: Volume is the type for remote storage volumes KVolumeMountTypeTmpfsString: Tmpfs is the type for mounting tmpfs KVolumeMountTypeNpipeString: NPipe is the type for mounting Windows named pipes Source: path inside the host machine Target: path inside the container after container start Note: For a complete list of volumes exposed by image, use ImageListExposedVolumes(id) and ImageListExposedVolumesByName(name) containerNetwork: container network configuration Note: please, use NetworkCreate() for correct configuration of network
ContainerCreateAndStart (Português): Cria um container, automaticamente expões as portas listas na imagem e depois o inicia
imageName: nome da image para download e pull containerName: nome do container (deve ser único) restartPolicy: KRestartPolicyNo - Não reinicia o container automaticamente. KRestartPolicyOnFailure - Reinicia o container ser ele terminar por error, com o manifesto contendo um valore de erro diferente de zero. KRestartPolicyAlways - Sempre reinicia o container se ele parar. Caso o container seja parado, ele só reinicia se o Docker daemon reiniciar ou com reinício manual (Veja 'second bullet' nas políticas de reinício do container) KRestartPolicyUnlessStopped - Similar ao always, exceto quando o container é parado (manualmente ou não) e não é reiniciado, mesmo quando o Docker daemon reinicia portExposedList: nat.PortMap lista de portas expostas do container key: string (número da porta do container/protocolo tcp|udp). Exemplo: "3000/tcp" value: []nat.PortBinding key: uma chave por porta no servidor hospedeiro value: struct{ HostPort: string numérica da porta no servidor hospedeiro }. Example: {HostPort: "3000"} mountVolumes: array de mount.Mount{} Type: KVolumeMountTypeBindString: Vincula uma pasta do computador, host, com uma pasta do container KVolumeMountTypeVolumeString: Volume é usado para arquivos de armazenamento remoto KVolumeMountTypeTmpfsString: Tmpfs arquiva os dados em memória RAM de forma volátil KVolumeMountTypeNpipeString: NPipe é um tipo de volume do Windows chamado de pipes Source: caminho dentro do computador, host Target: caminho dentro do container quando ele inicia Nota: Para uma lista completa de volumes expostos na imagem, use ImageListExposedVolumes(id) e ImageListExposedVolumesByName(name) containerNetwork: configuração de rede do container Nota: Por favor, use NetworkCreate() para a forma correta da configuração de rede
Example ¶
var err error var containerId string var imageId string var networkId string var dockerSys *DockerSystem var networkAutoConfiguration *NextNetworkAutoConfiguration var networkNextAddress *network.NetworkingConfig // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê _todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: 'static' folder path // Português: caminho da pasta 'static' var smallServerPathStatic string smallServerPathStatic = smallServerPath + string(os.PathSeparator) + "static" // English: 'index.html' file path // Português: caminho do arquivo 'index.html' var smallServerPathStaticContent string smallServerPathStaticContent = smallServerPathStatic + string(os.PathSeparator) + "index.html" // English: create a new default client. // Português: cria um novo cliente com configurações padrão. dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: create a network named 'network_delete_before_test' // Português: cria uma nova rede de nome 'network_delete_before_test' networkId, networkAutoConfiguration, err = dockerSys.NetworkCreate( "network_delete_before_test", KNetworkDriveBridge, "local", "10.0.0.0/16", "10.0.0.1", ) if err != nil { panic(err) } if networkId == "" { err = errors.New("network id was not generated") panic(err) } // English: get next ip address from network, '10.0.0.2' // Português: pega o próxima endereço da rede, '10.0.0.2' _, networkNextAddress, err = networkAutoConfiguration.GetNext() if err != nil { panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: mount and start a container // Português: monta i inicializa o container containerId, err = dockerSys.ContainerCreateAndStart( // image name "image_server_delete_before_test:latest", // container name "container_delete_before_test", // restart policy KRestartPolicyUnlessStopped, // portMap nat.PortMap{ // container port number/protocol [tpc/udp] "3000/tcp": []nat.PortBinding{ // server original port { // server output port number HostPort: "9002", }, }, }, // mount volumes []mount.Mount{ { // bind - is the type for mounting host dir (real folder inside computer where // this code work) Type: KVolumeMountTypeBindString, // path inside host machine Source: smallServerPathStatic, // path inside image Target: "/static", }, }, // nil or container network configuration networkNextAddress, ) if err != nil { panic(err) } if containerId == "" { err = errors.New("container id was not generated") panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true var page []byte var found int var response *http.Response // English: contents of the static server index.html page // Português: conteúdo da página index.html do servidor estático var htmlIndexContent1 = []byte("<!DOCTYPE html><html><body><p>I'm alive!</p></body></html>") err = ioutil.WriteFile(smallServerPathStaticContent, htmlIndexContent1, os.ModePerm) if err != nil { panic(err) } // English: takes the content from the server for testing // Português: pega o conteúdo do servidor para teste response, err = http.Get("http://localhost:9002") if err != nil { panic(err) } page, err = ioutil.ReadAll(response.Body) if err != nil { panic(err) } // English: compare content // Português: compara o conteúdo found = bytes.Compare(page, htmlIndexContent1) if found == 1 { err = errors.New("small server content error") panic(err) } // English: contents of the static server index.html page // Português: conteúdo da página index.html do servidor estático htmlIndexContent1 = []byte("<!DOCTYPE html><html><body><p>I'm alive Dr. Frankenstein!</p></body></html>") err = ioutil.WriteFile(smallServerPathStaticContent, htmlIndexContent1, os.ModePerm) if err != nil { panic(err) } // English: takes the content from the server for testing // Português: pega o conteúdo do servidor para teste response, err = http.Get("http://localhost:9002") if err != nil { panic(err) } page, err = ioutil.ReadAll(response.Body) if err != nil { panic(err) } // English: compare content // Português: compara o conteúdo found = bytes.Compare(page, htmlIndexContent1) if found == 1 { err = errors.New("small server content error") panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) ContainerCreateExposePortsAutomaticallyAndStart ¶
func (el *DockerSystem) ContainerCreateExposePortsAutomaticallyAndStart( imageName, containerName string, restartPolicy RestartPolicy, mountVolumes []mount.Mount, containerNetwork *network.NetworkingConfig, ) ( containerID string, err error, )
ContainerCreateExposePortsAutomaticallyAndStart (English): Creates a container, automatically exposes the ports listed in the image and start then
imageName: image name for download and pull containerName: unique container name restartPolicy: KRestartPolicyNo - Do not automatically restart the container. KRestartPolicyOnFailure - Restart the container if it exits due to an error, which manifests as a non-zero exit code. KRestartPolicyAlways - Always restart the container if it stops. If it is manually stopped, it is restarted only when Docker daemon restarts or the container itself is manually restarted. (See the second bullet listed in restart policy details) KRestartPolicyUnlessStopped - Similar to always, except that when the container is stopped (manually or otherwise), it is not restarted even after Docker daemon restarts. mountVolumes: array of mount.Mount{} Type: KVolumeMountTypeBindString: Bind is the type for mounting host dir (real folder inside computer where this code work) KVolumeMountTypeVolumeString: Volume is the type for remote storage volumes KVolumeMountTypeTmpfsString: Tmpfs is the type for mounting tmpfs KVolumeMountTypeNpipeString: NPipe is the type for mounting Windows named pipes Source: path inside the host machine Target: path inside the container after container start Note: For a complete list of volumes exposed by image, use ImageListExposedVolumes(id) and ImageListExposedVolumesByName(name) containerNetwork: container network configuration Note: please, use NetworkCreate() for correct configuration of network
ContainerCreateExposePortsAutomaticallyAndStart (Português): Cria um container, automaticamente expões as portas listas na imagem e o inicia
imageName: nome da image para download e pull containerName: nome do container (deve ser único) restartPolicy: KRestartPolicyNo - Não reinicia o container automaticamente. KRestartPolicyOnFailure - Reinicia o container ser ele terminar por error, com o manifesto contendo um valore de erro diferente de zero. KRestartPolicyAlways - Sempre reinicia o container se ele parar. Caso o container seja parado, ele só reinicia se o Docker daemon reiniciar ou com reinício manual (Veja 'second bullet' nas políticas de reinício do container) KRestartPolicyUnlessStopped - Similar ao always, exceto quando o container é parado (manualmente ou não) e não é reiniciado, mesmo quando o Docker daemon reinicia mountVolumes: array de mount.Mount{} Type: KVolumeMountTypeBindString: Vincula uma pasta do computador, host, com uma pasta do container KVolumeMountTypeVolumeString: Volume é usado para arquivos de armazenamento remoto KVolumeMountTypeTmpfsString: Tmpfs arquiva os dados em memória RAM de forma volátil KVolumeMountTypeNpipeString: NPipe é um tipo de volume do Windows chamado de pipes Source: caminho dentro do computador, host Target: caminho dentro do container quando ele inicia Nota: Para uma lista completa de volumes expostos na imagem, use ImageListExposedVolumes(id) e ImageListExposedVolumesByName(name) containerNetwork: configuração de rede do container Nota: Por favor, use NetworkCreate() para a forma correta da configuração de rede
Example ¶
var err error var containerId string var imageId string var networkId string var dockerSys *DockerSystem var networkAutoConfiguration *NextNetworkAutoConfiguration var networkNextAddress *network.NetworkingConfig // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: 'static' folder path // Português: caminho da pasta 'static' var smallServerPathStatic string smallServerPathStatic = smallServerPath + string(os.PathSeparator) + "static" // English: 'index.html' file path // Português: caminho do arquivo 'index.html' var smallServerPathStaticContent string smallServerPathStaticContent = smallServerPathStatic + string(os.PathSeparator) + "index.html" // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: create a network named 'network_delete_before_test' // Português: cria uma nova rede de nome 'network_delete_before_test' networkId, networkAutoConfiguration, err = dockerSys.NetworkCreate( "network_delete_before_test", KNetworkDriveBridge, "local", "10.0.0.0/16", "10.0.0.1", ) if err != nil { panic(err) } if networkId == "" { err = errors.New("network id was not generated") panic(err) } // English: get next ip address from network, '10.0.0.2' // Português: pega o próxima endereço da rede, '10.0.0.2' _, networkNextAddress, err = networkAutoConfiguration.GetNext() if err != nil { panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: mount and start a container // Português: monta i inicializa o container containerId, err = dockerSys.ContainerCreateExposePortsAutomaticallyAndStart( "image_server_delete_before_test:latest", // image name "container_delete_before_test", // container name KRestartPolicyUnlessStopped, // restart policy []mount.Mount{ // mount volumes { Type: KVolumeMountTypeBindString, // bind - is the type for mounting host dir // (real folder inside computer where this // code work) Source: smallServerPathStatic, // path inside host machine Target: "/static", // path inside image }, }, networkNextAddress, // [optional] container network ) if err != nil { panic(err) } if containerId == "" { err = errors.New("container id was not generated") panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true var page []byte var found int var response *http.Response // English: contents of the static server index.html page // Português: conteúdo da página index.html do servidor estático var htmlIndexContent1 = []byte("<!DOCTYPE html><html><body><p>I'm alive!</p></body></html>") err = ioutil.WriteFile(smallServerPathStaticContent, htmlIndexContent1, os.ModePerm) if err != nil { panic(err) } // English: takes the content from the server for testing // Português: pega o conteúdo do servidor para teste response, err = http.Get("http://localhost:3000") if err != nil { panic(err) } page, err = ioutil.ReadAll(response.Body) if err != nil { panic(err) } // English: compare content // Português: compara o conteúdo found = bytes.Compare(page, htmlIndexContent1) if found == 1 { err = errors.New("small server content error") panic(err) } // English: contents of the static server index.html page // Português: conteúdo da página index.html do servidor estático htmlIndexContent1 = []byte("<!DOCTYPE html><html><body><p>I'm alive Dr. Frankenstein!</p></body></html>") err = ioutil.WriteFile(smallServerPathStaticContent, htmlIndexContent1, os.ModePerm) if err != nil { panic(err) } // English: takes the content from the server for testing // Português: pega o conteúdo do servidor para teste response, err = http.Get("http://localhost:3000") if err != nil { panic(err) } page, err = ioutil.ReadAll(response.Body) if err != nil { panic(err) } // English: compare content // Português: compara o conteúdo found = bytes.Compare(page, htmlIndexContent1) if found == 1 { err = errors.New("small server content error") panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) ContainerCreateWithConfig ¶
func (el *DockerSystem) ContainerCreateWithConfig( configuration *container.Config, containerName string, restartPolicy RestartPolicy, portExposedList nat.PortMap, mountVolumes []mount.Mount, containerNetwork *network.NetworkingConfig, ) ( containerID string, warnings []string, err error, )
ContainerCreateWithConfig (English): Creates a container
configuration: todo: fazer containerName: unique container name restartPolicy: KRestartPolicyNo - Do not automatically restart the container. KRestartPolicyOnFailure - Restart the container if it exits due to an error, which manifests as a non-zero exit code. KRestartPolicyAlways - Always restart the container if it stops. If it is manually stopped, it is restarted only when Docker daemon restarts or the container itself is manually restarted. (See the second bullet listed in restart policy details) KRestartPolicyUnlessStopped - Similar to always, except that when the container is stopped (manually or otherwise), it is not restarted even after Docker daemon restarts. portExposedList: nat.PortMap exposed port list from container key: string (container port umber/protocol tcp|udp). Example: "3000/tcp" value: []nat.PortBinding key: one key per server host port value: struct{ HostPort: numeric string host port }. Example: {HostPort: "3000"} mountVolumes: array of mount.Mount{} Type: KVolumeMountTypeBindString: Bind is the type for mounting host dir (real folder inside computer where this code work) KVolumeMountTypeVolumeString: Volume is the type for remote storage volumes KVolumeMountTypeTmpfsString: Tmpfs is the type for mounting tmpfs KVolumeMountTypeNpipeString: NPipe is the type for mounting Windows named pipes Source: path inside the host machine Target: path inside the container after container start Note: For a complete list of volumes exposed by image, use ImageListExposedVolumes(id) and ImageListExposedVolumesByName(name) containerNetwork: container network configuration Note: please, use NetworkCreate() for correct configuration of network
ContainerCreate (Português): Cria um container listas na imagem
imageName: nome da image para download e pull containerName: nome do container (deve ser único) restartPolicy: KRestartPolicyNo - Não reinicia o container automaticamente. KRestartPolicyOnFailure - Reinicia o container ser ele terminar por error, com o manifesto contendo um valore de erro diferente de zero. KRestartPolicyAlways - Sempre reinicia o container se ele parar. Caso o container seja parado, ele só reinicia se o Docker daemon reiniciar ou com reinício manual (Veja 'second bullet' nas políticas de reinício do container) KRestartPolicyUnlessStopped - Similar ao always, exceto quando o container é parado (manualmente ou não) e não é reiniciado, mesmo quando o Docker daemon reinicia portExposedList: nat.PortMap lista de portas expostas do container key: string (número da porta do container/protocolo tcp|udp). Exemplo: "3000/tcp" value: []nat.PortBinding key: uma chave por porta no servidor hospedeiro value: struct{ HostPort: string numérica da porta no servidor hospedeiro }. Example: {HostPort: "3000"} mountVolumes: array de mount.Mount{} Type: KVolumeMountTypeBindString: Vincula uma pasta do computador, host, com uma pasta do container KVolumeMountTypeVolumeString: Volume é usado para arquivos de armazenamento remoto KVolumeMountTypeTmpfsString: Tmpfs arquiva os dados em memória RAM de forma volátil KVolumeMountTypeNpipeString: NPipe é um tipo de volume do Windows chamado de pipes Source: caminho dentro do computador, host Target: caminho dentro do container quando ele inicia Nota: Para uma lista completa de volumes expostos na imagem, use ImageListExposedVolumes(id) e ImageListExposedVolumesByName(name) containerNetwork: configuração de rede do container Nota: Por favor, use NetworkCreate() para a forma correta da configuração de rede
func (*DockerSystem) ContainerExecCommand ¶
func (el *DockerSystem) ContainerExecCommand( id string, commands []string, ) ( exitCode int, running bool, stdOutput []byte, stdError []byte, err error, )
Example ¶
var err error var containerId string var imageId string var networkId string var dockerSys *DockerSystem var networkAutoConfiguration *NextNetworkAutoConfiguration var networkNextAddress *network.NetworkingConfig // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem // log.Printf("image pull status: %+v\n", status) if status.Closed == true { // log.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: 'static' folder path // Português: caminho da pasta 'static' var smallServerPathStatic string smallServerPathStatic = smallServerPath + string(os.PathSeparator) + "static" // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: create a network named 'network_delete_before_test' // Português: cria uma nova rede de nome 'network_delete_before_test' networkId, networkAutoConfiguration, err = dockerSys.NetworkCreate( "network_delete_before_test", KNetworkDriveBridge, "local", "10.0.0.0/16", "10.0.0.1", ) if err != nil { panic(err) } if networkId == "" { err = errors.New("network id was not generated") panic(err) } // English: get next ip address from network, '10.0.0.2' // Português: pega o próxima endereço da rede, '10.0.0.2' _, networkNextAddress, err = networkAutoConfiguration.GetNext() if err != nil { panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: mount and start a container // Português: monta i inicializa o container containerId, _, err = dockerSys.ContainerCreateWithConfig( // image name &container.Config{ Image: "image_server_delete_before_test:latest", }, // container name "container_delete_before_test", // restart policy KRestartPolicyUnlessStopped, // portMap nat.PortMap{ // container port number/protocol [tpc/udp] "3000/tcp": []nat.PortBinding{ // server original port { // server output port number HostPort: "9002", }, }, }, // mount volumes []mount.Mount{ { // bind - is the type for mounting host dir (real folder inside computer where // this code work) Type: KVolumeMountTypeBindString, // path inside host machine Source: smallServerPathStatic, // path inside image Target: "/static", }, }, // nil or container network configuration networkNextAddress, ) if err != nil { panic(err) } if containerId == "" { err = errors.New("container id was not generated") panic(err) } err = dockerSys.ContainerStart(containerId) if err != nil { panic(err) } // English: find a container ID by name // Português: procura o ID do container por nome var containerFoundId string containerFoundId, err = dockerSys.ContainerFindIdByName("container_delete_before_test") if err != nil { panic(err) } if containerId != containerFoundId { err = errors.New("wrong container id") panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true _, _, _, _, err = dockerSys.ContainerExecCommand(containerId, []string{`/test.sh`}) if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) ContainerFindIdByName ¶
func (el *DockerSystem) ContainerFindIdByName( name string, ) ( ID string, err error, )
ContainerFindIdByName (English): Searches for the container name and returns the ID of the container
name: string container name
ContainerFindIdByName (Português): Procura pelo nome do container e retorna o ID do mesmo
name: string nome do container
Example ¶
var err error var containerId string var imageId string var networkId string var dockerSys *DockerSystem var networkAutoConfiguration *NextNetworkAutoConfiguration var networkNextAddress *network.NetworkingConfig // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: 'static' folder path // Português: caminho da pasta 'static' var smallServerPathStatic string smallServerPathStatic = smallServerPath + string(os.PathSeparator) + "static" // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: create a network named 'network_delete_before_test' // Português: cria uma nova rede de nome 'network_delete_before_test' networkId, networkAutoConfiguration, err = dockerSys.NetworkCreate( "network_delete_before_test", KNetworkDriveBridge, "local", "10.0.0.0/16", "10.0.0.1", ) if err != nil { panic(err) } if networkId == "" { err = errors.New("network id was not generated") panic(err) } // English: get next ip address from network, '10.0.0.2' // Português: pega o próxima endereço da rede, '10.0.0.2' _, networkNextAddress, err = networkAutoConfiguration.GetNext() if err != nil { panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: mount and start a container // Português: monta i inicializa o container containerId, err = dockerSys.ContainerCreate( // image name "image_server_delete_before_test:latest", // container name "container_delete_before_test", // restart policy KRestartPolicyUnlessStopped, // portMap nat.PortMap{ // container port number/protocol [tpc/udp] "3000/tcp": []nat.PortBinding{ // server original port { // server output port number HostPort: "9002", }, }, }, // mount volumes []mount.Mount{ { // bind - is the type for mounting host dir (real folder inside computer where // this code work) Type: KVolumeMountTypeBindString, // path inside host machine Source: smallServerPathStatic, // path inside image Target: "/static", }, }, // nil or container network configuration networkNextAddress, ) if err != nil { panic(err) } if containerId == "" { err = errors.New("container id was not generated") panic(err) } // English: find a container ID by name // Português: procura o ID do container por nome var containerFoundId string containerFoundId, err = dockerSys.ContainerFindIdByName("container_delete_before_test") if err != nil { panic(err) } if containerId != containerFoundId { err = errors.New("wrong container id") panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) ContainerFindIdByNameContains ¶
func (el *DockerSystem) ContainerFindIdByNameContains( containsName string, ) ( list []NameAndId, err error, )
ContainerFindIdByNameContains (English): Search by part of the container name and returns a list of NameAndId
name: string part of the container name
ContainerFindIdByNameContains (Português): Procura por parte do nome do container e retorna uma lista de NameAndId
name: string parte do nome do container
Example ¶
var err error var containerId string var imageId string var networkId string var dockerSys *DockerSystem var networkAutoConfiguration *NextNetworkAutoConfiguration var networkNextAddress *network.NetworkingConfig // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: 'static' folder path // Português: caminho da pasta 'static' var smallServerPathStatic string smallServerPathStatic = smallServerPath + string(os.PathSeparator) + "static" // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: create a network named 'network_delete_before_test' // Português: cria uma nova rede de nome 'network_delete_before_test' networkId, networkAutoConfiguration, err = dockerSys.NetworkCreate( "network_delete_before_test", KNetworkDriveBridge, "local", "10.0.0.0/16", "10.0.0.1", ) if err != nil { panic(err) } if networkId == "" { err = errors.New("network id was not generated") panic(err) } // English: get next ip address from network, '10.0.0.2' // Português: pega o próxima endereço da rede, '10.0.0.2' _, networkNextAddress, err = networkAutoConfiguration.GetNext() if err != nil { panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: mount and start a container // Português: monta i inicializa o container containerId, err = dockerSys.ContainerCreate( // image name "image_server_delete_before_test:latest", // container name "container_delete_before_test", // restart policy KRestartPolicyUnlessStopped, // portMap nat.PortMap{ // container port number/protocol [tpc/udp] "3000/tcp": []nat.PortBinding{ // server original port { // server output port number HostPort: "9002", }, }, }, // mount volumes []mount.Mount{ { // bind - is the type for mounting host dir (real folder inside computer where // this code work) Type: KVolumeMountTypeBindString, // path inside host machine Source: smallServerPathStatic, // path inside image Target: "/static", }, }, // nil or container network configuration networkNextAddress, ) if err != nil { panic(err) } if containerId == "" { err = errors.New("container id was not generated") panic(err) } // English: find container by part of name // Português: procura um container por parte do nome var containerFoundIdList []NameAndId containerFoundIdList, err = dockerSys.ContainerFindIdByNameContains("delete") if err != nil { panic(err) } if len(containerFoundIdList) == 0 { err = errors.New("container name contains 'delete' not found") panic(err) } if containerId != containerFoundIdList[0].ID { err = errors.New("wrong container id") panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) ContainerInspect ¶
func (el *DockerSystem) ContainerInspect( id string, ) ( inspect types.ContainerJSON, err error, )
ContainerInspect (English): Inspect the container
id: string container ID
ContainerInspect (Português): Inspeciona o container
id: string ID do container
Example ¶
var err error var containerId string var imageId string var networkId string var dockerSys *DockerSystem var networkAutoConfiguration *NextNetworkAutoConfiguration var networkNextAddress *network.NetworkingConfig // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: 'static' folder path // Português: caminho da pasta 'static' var smallServerPathStatic string smallServerPathStatic = smallServerPath + string(os.PathSeparator) + "static" // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: create a network named 'network_delete_before_test' // Português: cria uma nova rede de nome 'network_delete_before_test' networkId, networkAutoConfiguration, err = dockerSys.NetworkCreate( "network_delete_before_test", KNetworkDriveBridge, "local", "10.0.0.0/16", "10.0.0.1", ) if err != nil { panic(err) } if networkId == "" { err = errors.New("network id was not generated") panic(err) } // English: get next ip address from network, '10.0.0.2' // Português: pega o próxima endereço da rede, '10.0.0.2' _, networkNextAddress, err = networkAutoConfiguration.GetNext() if err != nil { panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: mount and start a container // Português: monta i inicializa o container containerId, err = dockerSys.ContainerCreate( // image name "image_server_delete_before_test:latest", // container name "container_delete_before_test", // restart policy KRestartPolicyUnlessStopped, // portMap nat.PortMap{ // container port number/protocol [tpc/udp] "3000/tcp": []nat.PortBinding{ // server original port { // server output port number HostPort: "9002", }, }, }, // mount volumes []mount.Mount{ { // bind - is the type for mounting host dir (real folder inside computer where // this code work) Type: KVolumeMountTypeBindString, // path inside host machine Source: smallServerPathStatic, // path inside image Target: "/static", }, }, // nil or container network configuration networkNextAddress, ) if err != nil { panic(err) } if containerId == "" { err = errors.New("container id was not generated") panic(err) } // English: start a container by id // Português: inicia um container por id err = dockerSys.ContainerStart(containerId) if err != nil { panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true // English: inspect a container by ID // Português: inspeciona um container por ID var inspect types.ContainerJSON inspect, err = dockerSys.ContainerInspect(containerId) if err != nil { panic(err) } if inspect.Name != "/container_delete_before_test" { err = errors.New("wrong container name") panic(err) } if inspect.State == nil { err = errors.New("container not running") panic(err) } if inspect.State.Running == false { err = errors.New("container not running") panic(err) } if len(inspect.Config.ExposedPorts) == 0 { err = errors.New("container not running") panic(err) } if reflect.ValueOf(inspect.Config.ExposedPorts["3000/tcp"]).IsZero() == false { err = errors.New("exposed ports fail") panic(err) } if len(inspect.NetworkSettings.Networks) != 1 { err = errors.New("IPv4 address error") panic(err) } if inspect.NetworkSettings.Networks["network_delete_before_test"].IPAddress != "10.0.0.2" { err = errors.New("IPv4 address error") panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) ContainerInspectByName ¶
func (el *DockerSystem) ContainerInspectByName( name string, ) ( inspect types.ContainerJSON, err error, )
ContainerInspectByName (English): Inspect the container by name
name: string container name
ContainerInspectByName (Português): Inspeciona o container pelo nome
name: string nome do container
Example ¶
var err error var containerId string var imageId string var networkId string var dockerSys *DockerSystem var networkAutoConfiguration *NextNetworkAutoConfiguration var networkNextAddress *network.NetworkingConfig // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: 'static' folder path // Português: caminho da pasta 'static' var smallServerPathStatic string smallServerPathStatic = smallServerPath + string(os.PathSeparator) + "static" // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: create a network named 'network_delete_before_test' // Português: cria uma nova rede de nome 'network_delete_before_test' networkId, networkAutoConfiguration, err = dockerSys.NetworkCreate( "network_delete_before_test", KNetworkDriveBridge, "local", "10.0.0.0/16", "10.0.0.1", ) if err != nil { panic(err) } if networkId == "" { err = errors.New("network id was not generated") panic(err) } // English: get next ip address from network, '10.0.0.2' // Português: pega o próxima endereço da rede, '10.0.0.2' _, networkNextAddress, err = networkAutoConfiguration.GetNext() if err != nil { panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: mount and start a container // Português: monta i inicializa o container containerId, err = dockerSys.ContainerCreate( // image name "image_server_delete_before_test:latest", // container name "container_delete_before_test", // restart policy KRestartPolicyUnlessStopped, // portMap nat.PortMap{ // container port number/protocol [tpc/udp] "3000/tcp": []nat.PortBinding{ // server original port { // server output port number HostPort: "9002", }, }, }, // mount volumes []mount.Mount{ { // bind - is the type for mounting host dir (real folder inside computer where // this code work) Type: KVolumeMountTypeBindString, // path inside host machine Source: smallServerPathStatic, // path inside image Target: "/static", }, }, // nil or container network configuration networkNextAddress, ) if err != nil { panic(err) } if containerId == "" { err = errors.New("container id was not generated") panic(err) } // English: start a container by id // Português: inicia um container por id err = dockerSys.ContainerStart(containerId) if err != nil { panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true // English: inspect a container by name // Português: inspeciona um container por nome var inspect types.ContainerJSON inspect, err = dockerSys.ContainerInspectByName("container_delete_before_test") if err != nil { panic(err) } if inspect.Name != "/container_delete_before_test" { err = errors.New("wrong container name") panic(err) } if inspect.State == nil { err = errors.New("container not running") panic(err) } if inspect.State.Running == false { err = errors.New("container not running") panic(err) } if len(inspect.Config.ExposedPorts) == 0 { err = errors.New("container not running") panic(err) } if reflect.ValueOf(inspect.Config.ExposedPorts["3000/tcp"]).IsZero() == false { err = errors.New("exposed ports fail") panic(err) } if len(inspect.NetworkSettings.Networks) != 1 { err = errors.New("IPv4 address error") panic(err) } if inspect.NetworkSettings.Networks["network_delete_before_test"].IPAddress != "10.0.0.2" { err = errors.New("IPv4 address error") panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) ContainerInspectByNameContains ¶
func (el *DockerSystem) ContainerInspectByNameContains( searchTerm string, ) ( list []types.ContainerJSON, err error, )
ContainerInspectByNameContains (English): Inspects all containers whose part of the name contains the search term
name: string search term
ContainerInspectByNameContains (Português): Inspeciona todos os containers com cuja parte do nome contém o termo procurado
name: string termo procurado
Example ¶
var err error var containerId string var imageId string var networkId string var dockerSys *DockerSystem var networkAutoConfiguration *NextNetworkAutoConfiguration var networkNextAddress *network.NetworkingConfig // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: 'static' folder path // Português: caminho da pasta 'static' var smallServerPathStatic string smallServerPathStatic = smallServerPath + string(os.PathSeparator) + "static" // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: create a network named 'network_delete_before_test' // Português: cria uma nova rede de nome 'network_delete_before_test' networkId, networkAutoConfiguration, err = dockerSys.NetworkCreate( "network_delete_before_test", KNetworkDriveBridge, "local", "10.0.0.0/16", "10.0.0.1", ) if err != nil { panic(err) } if networkId == "" { err = errors.New("network id was not generated") panic(err) } // English: get next ip address from network, '10.0.0.2' // Português: pega o próxima endereço da rede, '10.0.0.2' _, networkNextAddress, err = networkAutoConfiguration.GetNext() if err != nil { panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: mount and start a container // Português: monta i inicializa o container containerId, err = dockerSys.ContainerCreate( // image name "image_server_delete_before_test:latest", // container name "container_delete_before_test", // restart policy KRestartPolicyUnlessStopped, // portMap nat.PortMap{ // container port number/protocol [tpc/udp] "3000/tcp": []nat.PortBinding{ // server original port { // server output port number HostPort: "9002", }, }, }, // mount volumes []mount.Mount{ { // bind - is the type for mounting host dir (real folder inside computer where // this code work) Type: KVolumeMountTypeBindString, // path inside host machine Source: smallServerPathStatic, // path inside image Target: "/static", }, }, // nil or container network configuration networkNextAddress, ) if err != nil { panic(err) } if containerId == "" { err = errors.New("container id was not generated") panic(err) } // English: start a container by id // Português: inicia um container por id err = dockerSys.ContainerStart(containerId) if err != nil { panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true // English: inspect a container by Name // Português: inspeciona um container por Name var inspectList []types.ContainerJSON inspectList, err = dockerSys.ContainerInspectByNameContains("delete") if err != nil { panic(err) } if len(inspectList) == 0 { err = errors.New("container name contains 'delete' not found") panic(err) } if inspectList[0].Name != "/container_delete_before_test" { err = errors.New("wrong container name") panic(err) } if inspectList[0].State == nil { err = errors.New("container not running") panic(err) } if inspectList[0].State.Running == false { err = errors.New("container not running") panic(err) } if len(inspectList[0].Config.ExposedPorts) == 0 { err = errors.New("container not running") panic(err) } if reflect.ValueOf(inspectList[0].Config.ExposedPorts["3000/tcp"]).IsZero() == false { err = errors.New("exposed ports fail") panic(err) } if len(inspectList[0].NetworkSettings.Networks) != 1 { err = errors.New("IPv4 address error") panic(err) } if inspectList[0].NetworkSettings.Networks["network_delete_before_test"].IPAddress != "10.0.0.2" { err = errors.New("IPv4 address error") log.Printf("current ip %v", inspectList[0].NetworkSettings.Networks["network_delete_before_test"].IPAddress) panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) ContainerInspectJSon ¶
func (el *DockerSystem) ContainerInspectJSon( id string, ) ( inspect []byte, err error, )
ContainerInspectJSon (English): Inspect the container by ID e return a json
name: string container ID
ContainerInspectJSon (Português): Inspeciona o container pelo ID e retorna um json
name: string ID do container
Example ¶
var err error var containerId string var imageId string var networkId string var dockerSys *DockerSystem var networkAutoConfiguration *NextNetworkAutoConfiguration var networkNextAddress *network.NetworkingConfig // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: 'static' folder path // Português: caminho da pasta 'static' var smallServerPathStatic string smallServerPathStatic = smallServerPath + string(os.PathSeparator) + "static" // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: create a network named 'network_delete_before_test' // Português: cria uma nova rede de nome 'network_delete_before_test' networkId, networkAutoConfiguration, err = dockerSys.NetworkCreate( "network_delete_before_test", KNetworkDriveBridge, "local", "10.0.0.0/16", "10.0.0.1", ) if err != nil { panic(err) } if networkId == "" { err = errors.New("network id was not generated") panic(err) } // English: get next ip address from network, '10.0.0.2' // Português: pega o próxima endereço da rede, '10.0.0.2' _, networkNextAddress, err = networkAutoConfiguration.GetNext() if err != nil { panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: mount and start a container // Português: monta i inicializa o container containerId, err = dockerSys.ContainerCreate( // image name "image_server_delete_before_test:latest", // container name "container_delete_before_test", // restart policy KRestartPolicyUnlessStopped, // portMap nat.PortMap{ // container port number/protocol [tpc/udp] "3000/tcp": []nat.PortBinding{ // server original port { // server output port number HostPort: "9002", }, }, }, // mount volumes []mount.Mount{ { // bind - is the type for mounting host dir (real folder inside computer where // this code work) Type: KVolumeMountTypeBindString, // path inside host machine Source: smallServerPathStatic, // path inside image Target: "/static", }, }, // nil or container network configuration networkNextAddress, ) if err != nil { panic(err) } if containerId == "" { err = errors.New("container id was not generated") panic(err) } // English: start a container by id // Português: inicia um container por id err = dockerSys.ContainerStart(containerId) if err != nil { panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true // English: inspect a container by ID // Português: inspeciona um container por ID var inspect types.ContainerJSON var jsonData []byte jsonData, err = dockerSys.ContainerInspectJSon(containerId) if err != nil { panic(err) } err = json.Unmarshal(jsonData, &inspect) if err != nil { panic(err) } if inspect.Name != "/container_delete_before_test" { err = errors.New("wrong container name") panic(err) } if inspect.State == nil { err = errors.New("container not running") panic(err) } if inspect.State.Running == false { err = errors.New("container not running") panic(err) } if len(inspect.Config.ExposedPorts) == 0 { err = errors.New("container not running") panic(err) } if reflect.ValueOf(inspect.Config.ExposedPorts["3000/tcp"]).IsZero() == false { err = errors.New("exposed ports fail") panic(err) } if len(inspect.NetworkSettings.Networks) != 1 { err = errors.New("IPv4 address error") panic(err) } if inspect.NetworkSettings.Networks["network_delete_before_test"].IPAddress != "10.0.0.2" { err = errors.New("IPv4 address error") panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) ContainerInspectJSonByName ¶
func (el *DockerSystem) ContainerInspectJSonByName( name string, ) ( inspect []byte, err error, )
ContainerInspectJSonByName (English): Inspect the container by name e return a json
name: string container name
ContainerInspectJSonByName (Português): Inspeciona o container pelo nome e retorna um json
name: string nome do container
Example ¶
var err error var containerId string var imageId string var networkId string var dockerSys *DockerSystem var networkAutoConfiguration *NextNetworkAutoConfiguration var networkNextAddress *network.NetworkingConfig // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: 'static' folder path // Português: caminho da pasta 'static' var smallServerPathStatic string smallServerPathStatic = smallServerPath + string(os.PathSeparator) + "static" // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: create a network named 'network_delete_before_test' // Português: cria uma nova rede de nome 'network_delete_before_test' networkId, networkAutoConfiguration, err = dockerSys.NetworkCreate( "network_delete_before_test", KNetworkDriveBridge, "local", "10.0.0.0/16", "10.0.0.1", ) if err != nil { panic(err) } if networkId == "" { err = errors.New("network id was not generated") panic(err) } // English: get next ip address from network, '10.0.0.2' // Português: pega o próxima endereço da rede, '10.0.0.2' _, networkNextAddress, err = networkAutoConfiguration.GetNext() if err != nil { panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: mount and start a container // Português: monta i inicializa o container containerId, err = dockerSys.ContainerCreate( // image name "image_server_delete_before_test:latest", // container name "container_delete_before_test", // restart policy KRestartPolicyUnlessStopped, // portMap nat.PortMap{ // container port number/protocol [tpc/udp] "3000/tcp": []nat.PortBinding{ // server original port { // server output port number HostPort: "9002", }, }, }, // mount volumes []mount.Mount{ { // bind - is the type for mounting host dir (real folder inside computer where // this code work) Type: KVolumeMountTypeBindString, // path inside host machine Source: smallServerPathStatic, // path inside image Target: "/static", }, }, // nil or container network configuration networkNextAddress, ) if err != nil { panic(err) } if containerId == "" { err = errors.New("container id was not generated") panic(err) } // English: start a container by id // Português: inicia um container por id err = dockerSys.ContainerStart(containerId) if err != nil { panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true // English: inspect a container by ID // Português: inspeciona um container por ID var inspect types.ContainerJSON var jsonData []byte jsonData, err = dockerSys.ContainerInspectJSonByName("container_delete_before_test") if err != nil { panic(err) } err = json.Unmarshal(jsonData, &inspect) if err != nil { panic(err) } if inspect.Name != "/container_delete_before_test" { err = errors.New("wrong container name") panic(err) } if inspect.State == nil { err = errors.New("container not running") panic(err) } if inspect.State.Running == false { err = errors.New("container not running") panic(err) } if len(inspect.Config.ExposedPorts) == 0 { err = errors.New("container not running") panic(err) } if reflect.ValueOf(inspect.Config.ExposedPorts["3000/tcp"]).IsZero() == false { err = errors.New("exposed ports fail") panic(err) } if len(inspect.NetworkSettings.Networks) != 1 { err = errors.New("IPv4 address error") panic(err) } if inspect.NetworkSettings.Networks["network_delete_before_test"].IPAddress != "10.0.0.2" { err = errors.New("IPv4 address error") panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) ContainerInspectParsed ¶
func (el *DockerSystem) ContainerInspectParsed( id string, ) ( parsed ContainerInspect, err error, )
ContainerInspectParsed testing. do not use
func (*DockerSystem) ContainerListAll ¶
func (el *DockerSystem) ContainerListAll() ( list []types.Container, err error, )
ContainerListAll (English): List all containers
ContainerListAll (Português): Lista todos os containers
Example ¶
var err error var containerId string var imageId string var dockerSys *DockerSystem // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: 'static' folder path // Português: caminho da pasta 'static' var smallServerPathStatic string smallServerPathStatic = smallServerPath + string(os.PathSeparator) + "static" // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: mount and start a container // Português: monta i inicializa o container containerId, err = dockerSys.ContainerCreate( // image name "image_server_delete_before_test:latest", // container name "container_delete_before_test", // restart policy KRestartPolicyUnlessStopped, // portMap nat.PortMap{ // container port number/protocol [tpc/udp] "3000/tcp": []nat.PortBinding{ // server original port { // server output port number HostPort: "9002", }, }, }, // mount volumes []mount.Mount{ { // bind - is the type for mounting host dir (real folder inside computer where // this code work) Type: KVolumeMountTypeBindString, // path inside host machine Source: smallServerPathStatic, // path inside image Target: "/static", }, }, // nil or container network configuration nil, ) if err != nil { panic(err) } if containerId == "" { err = errors.New("container id was not generated") panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true // English: list all containers // Português: lista todos os containers var list []types.Container var pass = false list, err = dockerSys.ContainerListAll() if err != nil { panic(err) } for _, container := range list { if container.ID == containerId && container.Names[0] == "/container_delete_before_test" { pass = true break } } if pass == false { err = errors.New("container id not found") panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) ContainerListWithOptions ¶
func (el *DockerSystem) ContainerListWithOptions( quiet bool, size bool, all bool, latest bool, since string, before string, limit int, filters filters.Args, ) ( list []types.Container, err error, )
ContainerListWithOptions (English): List containers
quiet: bool size: bool populate types.Container.SiseRw and types.Container.SizeRootFs all: bool false for running containers only latest: bool since: string example: "2020-09-08T00:39:53.613203298Z" before: string example: "2020-09-08T00:39:53.613203298Z" limit: int
ContainerListWithOptions (Português): Lista containers
quiet: bool size: bool popula types.Container.SiseRw e types.Container.SizeRootFs all: bool false retorna apenas containers rodando latest: bool since: string exemplo: "2020-09-08T00:39:53.613203298Z" before: string exemplo: "2020-09-08T00:39:53.613203298Z" limit: int
Example ¶
var err error var containerId string var imageId string var dockerSys *DockerSystem // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: 'static' folder path // Português: caminho da pasta 'static' var smallServerPathStatic string smallServerPathStatic = smallServerPath + string(os.PathSeparator) + "static" // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: mount and start a container // Português: monta i inicializa o container containerId, err = dockerSys.ContainerCreateAndStart( // image name "image_server_delete_before_test:latest", // container name "container_delete_before_test", // restart policy KRestartPolicyUnlessStopped, // portMap nat.PortMap{ // container port number/protocol [tpc/udp] "3000/tcp": []nat.PortBinding{ // server original port { // server output port number HostPort: "9002", }, }, }, // mount volumes []mount.Mount{ { // bind - is the type for mounting host dir (real folder inside computer where // this code work) Type: KVolumeMountTypeBindString, // path inside host machine Source: smallServerPathStatic, // path inside image Target: "/static", }, }, // nil or container network configuration nil, ) if err != nil { panic(err) } if containerId == "" { err = errors.New("container id was not generated") panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true // English: list all containers // Português: lista todos os containers var list []types.Container var pass = false list, err = dockerSys.ContainerListWithOptions( false, false, false, false, "", "", 0, filters.Args{}, ) if err != nil { panic(err) } for _, container := range list { if container.ID == containerId && container.Names[0] == "/container_delete_before_test" { pass = true break } } if pass == false { err = errors.New("container id not found") panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) ContainerLogs ¶
func (el *DockerSystem) ContainerLogs( id string, ) ( log []byte, err error, )
ContainerLogs (English): Returns container std out
ContainerLogs (Português): Retorna a saída padrão do container
Example ¶
var err error var containerId string var imageId string var dockerSys *DockerSystem // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: 'static' folder path // Português: caminho da pasta 'static' var smallServerPathStatic string smallServerPathStatic = smallServerPath + string(os.PathSeparator) + "static" // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: mount and start a container // Português: monta i inicializa o container containerId, err = dockerSys.ContainerCreate( // image name "image_server_delete_before_test:latest", // container name "container_delete_before_test", // restart policy KRestartPolicyUnlessStopped, // portMap nat.PortMap{ // container port number/protocol [tpc/udp] "3000/tcp": []nat.PortBinding{ // server original port { // server output port number HostPort: "9002", }, }, }, // mount volumes []mount.Mount{ { // bind - is the type for mounting host dir (real folder inside computer where // this code work) Type: KVolumeMountTypeBindString, // path inside host machine Source: smallServerPathStatic, // path inside image Target: "/static", }, }, // nil or container network configuration nil, ) if err != nil { panic(err) } if containerId == "" { err = errors.New("container id was not generated") panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true // English: start a container by id // Português: inicia um container por id err = dockerSys.ContainerStart(containerId) if err != nil { panic(err) } // English: list all containers // Português: lista todos os containers var log []byte log, err = dockerSys.ContainerLogs(containerId) if err != nil { panic(err) } if bytes.Contains(log, []byte("starting server at port 3000")) == false { err = errors.New("expected log for container not found") panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) ContainerLogsWaitText ¶
func (el *DockerSystem) ContainerLogsWaitText( id string, text string, out io.Writer, ) ( logContainer []byte, err error, )
ContainerLogsWaitText (English):
ContainerLogsWaitText (Português):
Example ¶
var err error var containerId string var imageId string var networkId string var dockerSys *DockerSystem var networkAutoConfiguration *NextNetworkAutoConfiguration var networkNextAddress *network.NetworkingConfig // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: 'static' folder path // Português: caminho da pasta 'static' var smallServerPathStatic string smallServerPathStatic = smallServerPath + string(os.PathSeparator) + "static" // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: create a network named 'network_delete_before_test' // Português: cria uma nova rede de nome 'network_delete_before_test' networkId, networkAutoConfiguration, err = dockerSys.NetworkCreate( "network_delete_before_test", KNetworkDriveBridge, "local", "10.0.0.0/16", "10.0.0.1", ) if err != nil { panic(err) } if networkId == "" { err = errors.New("network id was not generated") panic(err) } // English: get next ip address from network, '10.0.0.2' // Português: pega o próxima endereço da rede, '10.0.0.2' _, networkNextAddress, err = networkAutoConfiguration.GetNext() if err != nil { panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: mount and start a container // Português: monta i inicializa o container containerId, err = dockerSys.ContainerCreate( "image_server_delete_before_test:latest", // image name "container_delete_before_test", // container name KRestartPolicyUnlessStopped, // restart policy nat.PortMap{ "3000/tcp": []nat.PortBinding{ // server original port { HostPort: "9002", // new output port }, }, }, []mount.Mount{ // mount volumes { Type: KVolumeMountTypeBindString, // bind - is the type for mounting host dir // (real folder inside computer where this // code work) Source: smallServerPathStatic, // path inside host machine Target: "/static", // path inside image }, }, networkNextAddress, // [optional] container network ) if err != nil { panic(err) } if containerId == "" { err = errors.New("container id was not generated") panic(err) } // English: container start // Português: inicia o container err = dockerSys.ContainerStart(containerId) if err != nil { panic(err) } _, err = dockerSys.ContainerLogsWaitText(containerId, "starting server at port 3000", nil) if err != nil { panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true var networkData ContainerNetworkDataList networkData, err = dockerSys.ContainerNetworkInspect(containerId) if err != nil { panic(err) } if networkData.GetNetworkIdByNetworkName("network_delete_before_test") != networkId { err = errors.New("network id error") panic(err) } if networkData.GetGatewayByNetworkName("network_delete_before_test") != "10.0.0.1" { err = errors.New("network gateway error") panic(err) } if networkData.GetIpAddressByNetworkName("network_delete_before_test") != "10.0.0.2" { err = errors.New("network IP address error") panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) ContainerLogsWaitTextWithTimeout ¶
func (el *DockerSystem) ContainerLogsWaitTextWithTimeout( id string, text string, timeout time.Duration, out io.Writer, ) ( logContainer []byte, err error, )
ContainerLogsWaitTextWithTimeout (English):
ContainerLogsWaitTextWithTimeout (Português):
Example ¶
var err error var containerId string var imageId string var networkId string var dockerSys *DockerSystem var networkAutoConfiguration *NextNetworkAutoConfiguration var networkNextAddress *network.NetworkingConfig // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: 'static' folder path // Português: caminho da pasta 'static' var smallServerPathStatic string smallServerPathStatic = smallServerPath + string(os.PathSeparator) + "static" // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: create a network named 'network_delete_before_test' // Português: cria uma nova rede de nome 'network_delete_before_test' networkId, networkAutoConfiguration, err = dockerSys.NetworkCreate( "network_delete_before_test", KNetworkDriveBridge, "local", "10.0.0.0/16", "10.0.0.1", ) if err != nil { panic(err) } if networkId == "" { err = errors.New("network id was not generated") panic(err) } // English: get next ip address from network, '10.0.0.2' // Português: pega o próxima endereço da rede, '10.0.0.2' _, networkNextAddress, err = networkAutoConfiguration.GetNext() if err != nil { panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: mount and start a container // Português: monta i inicializa o container containerId, err = dockerSys.ContainerCreate( "image_server_delete_before_test:latest", // image name "container_delete_before_test", // container name KRestartPolicyUnlessStopped, // restart policy nat.PortMap{ "3000/tcp": []nat.PortBinding{ // server original port { HostPort: "9002", // new output port }, }, }, []mount.Mount{ // mount volumes { Type: KVolumeMountTypeBindString, // bind - is the type for mounting host dir // (real folder inside computer where this // code work) Source: smallServerPathStatic, // path inside host machine Target: "/static", // path inside image }, }, networkNextAddress, // [optional] container network ) if err != nil { panic(err) } if containerId == "" { err = errors.New("container id was not generated") panic(err) } // English: container start // Português: inicia o container err = dockerSys.ContainerStart(containerId) if err != nil { panic(err) } var networkData ContainerNetworkDataList networkData, err = dockerSys.ContainerNetworkInspect(containerId) if err != nil { panic(err) } if networkData.GetNetworkIdByNetworkName("network_delete_before_test") != networkId { err = errors.New("network id error") panic(err) } if networkData.GetGatewayByNetworkName("network_delete_before_test") != "10.0.0.1" { err = errors.New("network gateway error") panic(err) } if networkData.GetIpAddressByNetworkName("network_delete_before_test") != "10.0.0.2" { err = errors.New("network IP address error") panic(err) } err = dockerSys.ContainerStop(containerId) if err != nil { panic(err) } _, err = dockerSys.ContainerLogsWaitTextWithTimeout(containerId, "wrong text", 15*time.Second, nil) if err != nil && err.Error() != "timeout" { panic(err) } if err == nil { err = errors.New("this test must be a timeout error") panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) ContainerNetworkInspect ¶
func (el *DockerSystem) ContainerNetworkInspect( id string, ) ( netDataList ContainerNetworkDataList, err error, )
ContainerNetworkInspect (English): Returns athe network data from a container
id: string container id
ContainerNetworkInspect (Português): Retorna os dados da rede do container
id: string container id
Example ¶
var err error var containerId string var imageId string var networkId string var dockerSys *DockerSystem var networkAutoConfiguration *NextNetworkAutoConfiguration var networkNextAddress *network.NetworkingConfig // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: 'static' folder path // Português: caminho da pasta 'static' var smallServerPathStatic string smallServerPathStatic = smallServerPath + string(os.PathSeparator) + "static" // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: create a network named 'network_delete_before_test' // Português: cria uma nova rede de nome 'network_delete_before_test' networkId, networkAutoConfiguration, err = dockerSys.NetworkCreate( "network_delete_before_test", KNetworkDriveBridge, "local", "10.0.0.0/16", "10.0.0.1", ) if err != nil { panic(err) } if networkId == "" { err = errors.New("network id was not generated") panic(err) } // English: get next ip address from network, '10.0.0.2' // Português: pega o próxima endereço da rede, '10.0.0.2' _, networkNextAddress, err = networkAutoConfiguration.GetNext() if err != nil { panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: mount and start a container // Português: monta i inicializa o container containerId, err = dockerSys.ContainerCreate( "image_server_delete_before_test:latest", // image name "container_delete_before_test", // container name KRestartPolicyUnlessStopped, // restart policy nat.PortMap{ "3000/tcp": []nat.PortBinding{ // server original port { HostPort: "9002", // new output port }, }, }, []mount.Mount{ // mount volumes { Type: KVolumeMountTypeBindString, // bind - is the type for mounting host dir // (real folder inside computer where this // code work) Source: smallServerPathStatic, // path inside host machine Target: "/static", // path inside image }, }, networkNextAddress, // [optional] container network ) if err != nil { panic(err) } if containerId == "" { err = errors.New("container id was not generated") panic(err) } // English: container start // Português: inicia o container err = dockerSys.ContainerStart(containerId) if err != nil { panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true var networkData ContainerNetworkDataList networkData, err = dockerSys.ContainerNetworkInspect(containerId) if err != nil { panic(err) } if networkData.GetNetworkIdByNetworkName("network_delete_before_test") != networkId { err = errors.New("network id error") panic(err) } if networkData.GetGatewayByNetworkName("network_delete_before_test") != "10.0.0.1" { err = errors.New("network gateway error") panic(err) } if networkData.GetIpAddressByNetworkName("network_delete_before_test") != "10.0.0.2" { err = errors.New("network IP address error") panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) ContainerPause ¶
func (el *DockerSystem) ContainerPause( id string, ) ( err error, )
Example ¶
var err error var containerId string var imageId string var networkId string var dockerSys *DockerSystem var networkAutoConfiguration *NextNetworkAutoConfiguration var networkNextAddress *network.NetworkingConfig // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: 'static' folder path // Português: caminho da pasta 'static' var smallServerPathStatic string smallServerPathStatic = smallServerPath + string(os.PathSeparator) + "static" // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: create a network named 'network_delete_before_test' // Português: cria uma nova rede de nome 'network_delete_before_test' networkId, networkAutoConfiguration, err = dockerSys.NetworkCreate( "network_delete_before_test", KNetworkDriveBridge, "local", "10.0.0.0/16", "10.0.0.1", ) if err != nil { panic(err) } if networkId == "" { err = errors.New("network id was not generated") panic(err) } // English: get next ip address from network, '10.0.0.2' // Português: pega o próxima endereço da rede, '10.0.0.2' _, networkNextAddress, err = networkAutoConfiguration.GetNext() if err != nil { panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: mount and start a container // Português: monta i inicializa o container containerId, err = dockerSys.ContainerCreate( "image_server_delete_before_test:latest", // image name "container_delete_before_test", // container name KRestartPolicyUnlessStopped, // restart policy nat.PortMap{ "3000/tcp": []nat.PortBinding{ // server original port { HostPort: "9002", // new output port }, }, }, []mount.Mount{ // mount volumes { Type: KVolumeMountTypeBindString, // bind - is the type for mounting host dir // (real folder inside computer where this // code work) Source: smallServerPathStatic, // path inside host machine Target: "/static", // path inside image }, }, networkNextAddress, // [optional] container network ) if err != nil { panic(err) } if containerId == "" { err = errors.New("container id was not generated") panic(err) } // English: container start // Português: inicia o container err = dockerSys.ContainerStart(containerId) if err != nil { panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true err = dockerSys.ContainerPause(containerId) if err != nil { panic(err) } err = dockerSys.ContainerUnpause(containerId) if err != nil { panic(err) } err = dockerSys.ContainerStop(containerId) if err != nil { panic(err) } err = dockerSys.ContainerRemove(containerId, true, false, false) if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) ContainerRemove ¶
func (el *DockerSystem) ContainerRemove( id string, removeVolumes, removeLinks, force bool, ) ( err error, )
ContainerRemove (English): Remove a container by id
id: string container id removeVolumes: bool remove container and volumes removeLinks: bool remove container and links force: bool force remove
ContainerRemove (Português): Remove container por id
id: string container id removeVolumes: bool remove o container e os volumes removeLinks: bool remove o container e os links force: bool força a emoção
Example ¶
var err error var containerId string var imageId string var networkId string var dockerSys *DockerSystem var networkAutoConfiguration *NextNetworkAutoConfiguration var networkNextAddress *network.NetworkingConfig // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: 'static' folder path // Português: caminho da pasta 'static' var smallServerPathStatic string smallServerPathStatic = smallServerPath + string(os.PathSeparator) + "static" // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: create a network named 'network_delete_before_test' // Português: cria uma nova rede de nome 'network_delete_before_test' networkId, networkAutoConfiguration, err = dockerSys.NetworkCreate( "network_delete_before_test", KNetworkDriveBridge, "local", "10.0.0.0/16", "10.0.0.1", ) if err != nil { panic(err) } if networkId == "" { err = errors.New("network id was not generated") panic(err) } // English: get next ip address from network, '10.0.0.2' // Português: pega o próxima endereço da rede, '10.0.0.2' _, networkNextAddress, err = networkAutoConfiguration.GetNext() if err != nil { panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: mount and start a container // Português: monta i inicializa o container containerId, err = dockerSys.ContainerCreate( "image_server_delete_before_test:latest", // image name "container_delete_before_test", // container name KRestartPolicyUnlessStopped, // restart policy nat.PortMap{ "3000/tcp": []nat.PortBinding{ // server original port { HostPort: "9002", // new output port }, }, }, []mount.Mount{ // mount volumes { Type: KVolumeMountTypeBindString, // bind - is the type for mounting host dir // (real folder inside computer where this // code work) Source: smallServerPathStatic, // path inside host machine Target: "/static", // path inside image }, }, networkNextAddress, // [optional] container network ) if err != nil { panic(err) } if containerId == "" { err = errors.New("container id was not generated") panic(err) } // English: container start // Português: inicia o container err = dockerSys.ContainerStart(containerId) if err != nil { panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true err = dockerSys.ContainerStop(containerId) if err != nil { panic(err) } err = dockerSys.ContainerRemove(containerId, true, false, false) if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) ContainerRestart ¶
func (el *DockerSystem) ContainerRestart( id string, ) ( err error, )
func (*DockerSystem) ContainerRestartWithTimeout ¶
func (el *DockerSystem) ContainerRestartWithTimeout( id string, timeout time.Duration, ) ( err error, )
func (*DockerSystem) ContainerStart ¶
func (el *DockerSystem) ContainerStart( id string, ) ( err error, )
ContainerStart (English): Start a container by id
id: string container id
ContainerStart (Português): Inicia um container por id
id: string container id
Example ¶
var err error var containerId string var imageId string var networkId string var dockerSys *DockerSystem var networkAutoConfiguration *NextNetworkAutoConfiguration var networkNextAddress *network.NetworkingConfig // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: 'static' folder path // Português: caminho da pasta 'static' var smallServerPathStatic string smallServerPathStatic = smallServerPath + string(os.PathSeparator) + "static" // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: create a network named 'network_delete_before_test' // Português: cria uma nova rede de nome 'network_delete_before_test' networkId, networkAutoConfiguration, err = dockerSys.NetworkCreate( "network_delete_before_test", KNetworkDriveBridge, "local", "10.0.0.0/16", "10.0.0.1", ) if err != nil { panic(err) } if networkId == "" { err = errors.New("network id was not generated") panic(err) } // English: get next ip address from network, '10.0.0.2' // Português: pega o próxima endereço da rede, '10.0.0.2' _, networkNextAddress, err = networkAutoConfiguration.GetNext() if err != nil { panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: mount and start a container // Português: monta i inicializa o container containerId, err = dockerSys.ContainerCreate( "image_server_delete_before_test:latest", // image name "container_delete_before_test", // container name KRestartPolicyUnlessStopped, // restart policy nat.PortMap{ "3000/tcp": []nat.PortBinding{ // server original port { HostPort: "9002", // new output port }, }, }, []mount.Mount{ // mount volumes { Type: KVolumeMountTypeBindString, // bind - is the type for mounting host dir // (real folder inside computer where this // code work) Source: smallServerPathStatic, // path inside host machine Target: "/static", // path inside image }, }, networkNextAddress, // [optional] container network ) if err != nil { panic(err) } if containerId == "" { err = errors.New("container id was not generated") panic(err) } // English: container start // Português: inicia o container err = dockerSys.ContainerStart(containerId) if err != nil { panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true err = dockerSys.ContainerStop(containerId) if err != nil { panic(err) } err = dockerSys.ContainerRemove(containerId, true, false, false) if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) ContainerStatisticsOneShot ¶
func (el *DockerSystem) ContainerStatisticsOneShot( id string, ) ( statsRet types.Stats, err error, )
ContainerStatisticsOneShot (English): Returns the performance information of the container in a timely manner
id: string container id
ContainerStatisticsOneShot (Português): Retorna as informações de desempenho do container de forma pontual
id: string container id
Example ¶
var err error var containerId string var imageId string var networkId string var dockerSys *DockerSystem var networkAutoConfiguration *NextNetworkAutoConfiguration var networkNextAddress *network.NetworkingConfig // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: 'static' folder path // Português: caminho da pasta 'static' var smallServerPathStatic string smallServerPathStatic = smallServerPath + string(os.PathSeparator) + "static" // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: create a network named 'network_delete_before_test' // Português: cria uma nova rede de nome 'network_delete_before_test' networkId, networkAutoConfiguration, err = dockerSys.NetworkCreate( "network_delete_before_test", KNetworkDriveBridge, "local", "10.0.0.0/16", "10.0.0.1", ) if err != nil { panic(err) } if networkId == "" { err = errors.New("network id was not generated") panic(err) } // English: get next ip address from network, '10.0.0.2' // Português: pega o próxima endereço da rede, '10.0.0.2' _, networkNextAddress, err = networkAutoConfiguration.GetNext() if err != nil { panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: mount and start a container // Português: monta i inicializa o container containerId, err = dockerSys.ContainerCreate( "image_server_delete_before_test:latest", // image name "container_delete_before_test", // container name KRestartPolicyUnlessStopped, // restart policy nat.PortMap{ "3000/tcp": []nat.PortBinding{ // server original port { HostPort: "9002", // new output port }, }, }, []mount.Mount{ // mount volumes { Type: KVolumeMountTypeBindString, // bind - is the type for mounting host dir // (real folder inside computer where this // code work) Source: smallServerPathStatic, // path inside host machine Target: "/static", // path inside image }, }, networkNextAddress, // [optional] container network ) if err != nil { panic(err) } if containerId == "" { err = errors.New("container id was not generated") panic(err) } // English: container start // Português: inicia o container err = dockerSys.ContainerStart(containerId) if err != nil { panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true var stats types.Stats stats, err = dockerSys.ContainerStatisticsOneShot(containerId) if err != nil { panic(err) } _ = stats if stats.CPUStats.OnlineCPUs == 0 { err = errors.New("container not running") panic(err) } if stats.CPUStats.CPUUsage.TotalUsage == 0 { err = errors.New("container not running") panic(err) } if stats.MemoryStats.Limit == 0 { err = errors.New("container not running") panic(err) } if stats.MemoryStats.Usage == 0 { err = errors.New("container not running") panic(err) } err = dockerSys.ContainerStop(containerId) if err != nil { panic(err) } err = dockerSys.ContainerRemove(containerId, true, false, false) if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) ContainerStatisticsOneShotByName ¶
func (el *DockerSystem) ContainerStatisticsOneShotByName( name string, ) ( ret types.Stats, err error, )
ContainerStatisticsOneShotByName (English): Returns the performance information of the container in a timely manner by name
name: string container name
ContainerStatisticsOneShotByName (Português): Retorna as informações de desempenho do container de forma pontual por nome
name: string container nome
Example ¶
var err error var containerId string var imageId string var networkId string var dockerSys *DockerSystem var networkAutoConfiguration *NextNetworkAutoConfiguration var networkNextAddress *network.NetworkingConfig // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: 'static' folder path // Português: caminho da pasta 'static' var smallServerPathStatic string smallServerPathStatic = smallServerPath + string(os.PathSeparator) + "static" // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: create a network named 'network_delete_before_test' // Português: cria uma nova rede de nome 'network_delete_before_test' networkId, networkAutoConfiguration, err = dockerSys.NetworkCreate( "network_delete_before_test", KNetworkDriveBridge, "local", "10.0.0.0/16", "10.0.0.1", ) if err != nil { panic(err) } if networkId == "" { err = errors.New("network id was not generated") panic(err) } // English: get next ip address from network, '10.0.0.2' // Português: pega o próxima endereço da rede, '10.0.0.2' _, networkNextAddress, err = networkAutoConfiguration.GetNext() if err != nil { panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: mount and start a container // Português: monta i inicializa o container containerId, err = dockerSys.ContainerCreate( "image_server_delete_before_test:latest", // image name "container_delete_before_test", // container name KRestartPolicyUnlessStopped, // restart policy nat.PortMap{ "3000/tcp": []nat.PortBinding{ // server original port { HostPort: "9002", // new output port }, }, }, []mount.Mount{ // mount volumes { Type: KVolumeMountTypeBindString, // bind - is the type for mounting host dir // (real folder inside computer where this // code work) Source: smallServerPathStatic, // path inside host machine Target: "/static", // path inside image }, }, networkNextAddress, // [optional] container network ) if err != nil { panic(err) } if containerId == "" { err = errors.New("container id was not generated") panic(err) } // English: container start // Português: inicia o container err = dockerSys.ContainerStart(containerId) if err != nil { panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true var stats types.Stats stats, err = dockerSys.ContainerStatisticsOneShotByName("container_delete_before_test") if err != nil { panic(err) } _ = stats if stats.CPUStats.OnlineCPUs == 0 { err = errors.New("container not running") panic(err) } if stats.CPUStats.CPUUsage.TotalUsage == 0 { err = errors.New("container not running") panic(err) } if stats.MemoryStats.Limit == 0 { err = errors.New("container not running") panic(err) } if stats.MemoryStats.Usage == 0 { err = errors.New("container not running") panic(err) } err = dockerSys.ContainerStop(containerId) if err != nil { panic(err) } err = dockerSys.ContainerRemove(containerId, true, false, false) if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) ContainerStop ¶
func (el *DockerSystem) ContainerStop( id string, ) ( err error, )
ContainerStop (English): Stop a container by id
id: string container id
ContainerStop (Português): Para um container por id
id: string container id
Example ¶
var err error var containerId string var imageId string var networkId string var dockerSys *DockerSystem var networkAutoConfiguration *NextNetworkAutoConfiguration var networkNextAddress *network.NetworkingConfig // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: 'static' folder path // Português: caminho da pasta 'static' var smallServerPathStatic string smallServerPathStatic = smallServerPath + string(os.PathSeparator) + "static" // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: create a network named 'network_delete_before_test' // Português: cria uma nova rede de nome 'network_delete_before_test' networkId, networkAutoConfiguration, err = dockerSys.NetworkCreate( "network_delete_before_test", KNetworkDriveBridge, "local", "10.0.0.0/16", "10.0.0.1", ) if err != nil { panic(err) } if networkId == "" { err = errors.New("network id was not generated") panic(err) } // English: get next ip address from network, '10.0.0.2' // Português: pega o próxima endereço da rede, '10.0.0.2' _, networkNextAddress, err = networkAutoConfiguration.GetNext() if err != nil { panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: mount and start a container // Português: monta i inicializa o container containerId, err = dockerSys.ContainerCreate( "image_server_delete_before_test:latest", // image name "container_delete_before_test", // container name KRestartPolicyUnlessStopped, // restart policy nat.PortMap{ "3000/tcp": []nat.PortBinding{ // server original port { HostPort: "9002", // new output port }, }, }, []mount.Mount{ // mount volumes { Type: KVolumeMountTypeBindString, // bind - is the type for mounting host dir // (real folder inside computer where this // code work) Source: smallServerPathStatic, // path inside host machine Target: "/static", // path inside image }, }, networkNextAddress, // [optional] container network ) if err != nil { panic(err) } if containerId == "" { err = errors.New("container id was not generated") panic(err) } // English: container start // Português: inicia o container err = dockerSys.ContainerStart(containerId) if err != nil { panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true err = dockerSys.ContainerStop(containerId) if err != nil { panic(err) } err = dockerSys.ContainerRemove(containerId, true, false, false) if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) ContainerStopAndRemove ¶
func (el *DockerSystem) ContainerStopAndRemove( id string, ) ( err error, )
Example ¶
var err error var containerId string var imageId string var networkId string var dockerSys *DockerSystem var networkAutoConfiguration *NextNetworkAutoConfiguration var networkNextAddress *network.NetworkingConfig // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: 'static' folder path // Português: caminho da pasta 'static' var smallServerPathStatic string smallServerPathStatic = smallServerPath + string(os.PathSeparator) + "static" // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: create a network named 'network_delete_before_test' // Português: cria uma nova rede de nome 'network_delete_before_test' networkId, networkAutoConfiguration, err = dockerSys.NetworkCreate( "network_delete_before_test", KNetworkDriveBridge, "local", "10.0.0.0/16", "10.0.0.1", ) if err != nil { panic(err) } if networkId == "" { err = errors.New("network id was not generated") panic(err) } // English: get next ip address from network, '10.0.0.2' // Português: pega o próxima endereço da rede, '10.0.0.2' _, networkNextAddress, err = networkAutoConfiguration.GetNext() if err != nil { panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: mount and start a container // Português: monta i inicializa o container containerId, err = dockerSys.ContainerCreate( "image_server_delete_before_test:latest", // image name "container_delete_before_test", // container name KRestartPolicyUnlessStopped, // restart policy nat.PortMap{ "3000/tcp": []nat.PortBinding{ // server original port { HostPort: "9002", // new output port }, }, }, []mount.Mount{ // mount volumes { Type: KVolumeMountTypeBindString, // bind - is the type for mounting host dir // (real folder inside computer where this // code work) Source: smallServerPathStatic, // path inside host machine Target: "/static", // path inside image }, }, networkNextAddress, // [optional] container network ) if err != nil { panic(err) } if containerId == "" { err = errors.New("container id was not generated") panic(err) } // English: container start // Português: inicia o container err = dockerSys.ContainerStart(containerId) if err != nil { panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true err = dockerSys.ContainerStopAndRemove(containerId) if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) ContainerUnpause ¶
func (el *DockerSystem) ContainerUnpause( id string, ) ( err error, )
func (*DockerSystem) ContainerWaitStatusNextExit ¶
func (el *DockerSystem) ContainerWaitStatusNextExit( id string, ) ( err error, )
ContainerWaitStatusNextExit (English): Waits until a container is in "next-exit" status
id: string container id
ContainerWaitStatusNextExit (Português): Aguarda até o container entrar no estado de "next-exit"
id: string container id
Example ¶
var err error var containerId string var imageId string var networkId string var dockerSys *DockerSystem var networkAutoConfiguration *NextNetworkAutoConfiguration var networkNextAddress *network.NetworkingConfig // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000_exit_after_15s") if err != nil { panic(err) } // English: 'static' folder path // Português: caminho da pasta 'static' var smallServerPathStatic string smallServerPathStatic = smallServerPath + string(os.PathSeparator) + "static" // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: create a network named 'network_delete_before_test' // Português: cria uma nova rede de nome 'network_delete_before_test' networkId, networkAutoConfiguration, err = dockerSys.NetworkCreate( "network_delete_before_test", KNetworkDriveBridge, "local", "10.0.0.0/16", "10.0.0.1", ) if err != nil { panic(err) } if networkId == "" { err = errors.New("network id was not generated") panic(err) } // English: get next ip address from network, '10.0.0.2' // Português: pega o próxima endereço da rede, '10.0.0.2' _, networkNextAddress, err = networkAutoConfiguration.GetNext() if err != nil { panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: mount and start a container // Português: monta i inicializa o container containerId, err = dockerSys.ContainerCreate( "image_server_delete_before_test:latest", // image name "container_delete_before_test", // container name KRestartPolicyUnlessStopped, // restart policy nat.PortMap{ "3000/tcp": []nat.PortBinding{ // server original port { HostPort: "9002", // new output port }, }, }, []mount.Mount{ // mount volumes { Type: KVolumeMountTypeBindString, // bind - is the type for mounting host dir // (real folder inside computer where this // code work) Source: smallServerPathStatic, // path inside host machine Target: "/static", // path inside image }, }, networkNextAddress, // [optional] container network ) if err != nil { panic(err) } if containerId == "" { err = errors.New("container id was not generated") panic(err) } // English: container start // Português: inicia o container err = dockerSys.ContainerStart(containerId) if err != nil { panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true err = dockerSys.ContainerWaitStatusNextExit(containerId) if err != nil { panic(err) } // English: list all containers // Português: lista todos os containers var log []byte log, err = dockerSys.ContainerLogs(containerId) if err != nil { panic(err) } if bytes.Contains(log, []byte("Bye...")) == false { err = errors.New("expected log for container not found") panic(err) } err = dockerSys.ContainerStop(containerId) if err != nil { panic(err) } err = dockerSys.ContainerRemove(containerId, true, false, false) if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) ContainerWaitStatusNotRunning ¶
func (el *DockerSystem) ContainerWaitStatusNotRunning( id string, timeout time.Duration, ) ( err error, )
ContainerWaitStatusNotRunning (English): Waits until a container is in "not-running" status
id: string container id
ContainerWaitStatusNotRunning (Português): Aguarda até o container entrar no estado de "not-running"
id: string container id
Example ¶
var err error var containerId string var imageId string var networkId string var dockerSys *DockerSystem var networkAutoConfiguration *NextNetworkAutoConfiguration var networkNextAddress *network.NetworkingConfig // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000_exit_after_15s") if err != nil { panic(err) } // English: 'static' folder path // Português: caminho da pasta 'static' var smallServerPathStatic string smallServerPathStatic = smallServerPath + string(os.PathSeparator) + "static" // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: create a network named 'network_delete_before_test' // Português: cria uma nova rede de nome 'network_delete_before_test' networkId, networkAutoConfiguration, err = dockerSys.NetworkCreate( "network_delete_before_test", KNetworkDriveBridge, "local", "10.0.0.0/16", "10.0.0.1", ) if err != nil { panic(err) } if networkId == "" { err = errors.New("network id was not generated") panic(err) } // English: get next ip address from network, '10.0.0.2' // Português: pega o próxima endereço da rede, '10.0.0.2' _, networkNextAddress, err = networkAutoConfiguration.GetNext() if err != nil { panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: mount and start a container // Português: monta i inicializa o container containerId, err = dockerSys.ContainerCreate( "image_server_delete_before_test:latest", // image name "container_delete_before_test", // container name KRestartPolicyNo, // restart policy nat.PortMap{ "3000/tcp": []nat.PortBinding{ // server original port { HostPort: "9002", // new output port }, }, }, []mount.Mount{ // mount volumes { Type: KVolumeMountTypeBindString, // bind - is the type for mounting host dir // (real folder inside computer where this // code work) Source: smallServerPathStatic, // path inside host machine Target: "/static", // path inside image }, }, networkNextAddress, // [optional] container network ) if err != nil { panic(err) } if containerId == "" { err = errors.New("container id was not generated") panic(err) } // English: container start // Português: inicia o container err = dockerSys.ContainerStart(containerId) if err != nil { panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true err = dockerSys.ContainerWaitStatusNotRunning(containerId, time.Minute) if err != nil { panic(err) } // English: list all containers // Português: lista todos os containers var log []byte log, err = dockerSys.ContainerLogs(containerId) if err != nil { panic(err) } if bytes.Contains(log, []byte("Bye...")) == false { err = errors.New("expected log for container not found") panic(err) } err = dockerSys.ContainerStop(containerId) if err != nil { panic(err) } err = dockerSys.ContainerRemove(containerId, true, false, false) if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) ContainerWaitStatusRemoved ¶
func (el *DockerSystem) ContainerWaitStatusRemoved( id string, ) ( err error, )
ContainerWaitStatusRemoved (English): Waits until a container is in "removed" status
id: string container id
ContainerWaitStatusRemoved (Português): Aguarda até o container entrar no estado de "removed"
id: string container id
Example ¶
var err error var containerId string var imageId string var networkId string var dockerSys *DockerSystem var networkAutoConfiguration *NextNetworkAutoConfiguration var networkNextAddress *network.NetworkingConfig // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê _todo o status da criação da imagem // fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: 'static' folder path // Português: caminho da pasta 'static' var smallServerPathStatic string smallServerPathStatic = smallServerPath + string(os.PathSeparator) + "static" // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: create a network named 'network_delete_before_test' // Português: cria uma nova rede de nome 'network_delete_before_test' networkId, networkAutoConfiguration, err = dockerSys.NetworkCreate( "network_delete_before_test", KNetworkDriveBridge, "local", "10.0.0.0/16", "10.0.0.1", ) if err != nil { panic(err) } if networkId == "" { err = errors.New("network id was not generated") panic(err) } // English: get next ip address from network, '10.0.0.2' // Português: pega o próxima endereço da rede, '10.0.0.2' _, networkNextAddress, err = networkAutoConfiguration.GetNext() if err != nil { panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: mount and start a container // Português: monta i inicializa o container containerId, err = dockerSys.ContainerCreate( "image_server_delete_before_test:latest", // image name "container_delete_before_test", // container name KRestartPolicyNo, // restart policy nat.PortMap{ "3000/tcp": []nat.PortBinding{ // server original port { HostPort: "9002", // new output port }, }, }, []mount.Mount{ // mount volumes { Type: KVolumeMountTypeBindString, // bind - is the type for mounting host dir // (real folder inside computer where this // code work) Source: smallServerPathStatic, // path inside host machine Target: "/static", // path inside image }, }, networkNextAddress, // [optional] container network ) if err != nil { panic(err) } if containerId == "" { err = errors.New("container id was not generated") panic(err) } // English: container start // Português: inicia o container err = dockerSys.ContainerStart(containerId) if err != nil { panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true ticker := time.NewTicker(15 * time.Second) go func(dockerSys *DockerSystem, containerId string) { var err error for { select { case <-ticker.C: err = dockerSys.ContainerStopAndRemove(containerId) if err != nil { panic(err) } return } } }(dockerSys, containerId) err = dockerSys.ContainerWaitStatusRemoved(containerId) if err != nil { panic(err) } // English: list all containers // Português: lista todos os containers var list []types.Container var pass = false list, err = dockerSys.ContainerListAll() if err != nil { panic(err) } for _, container := range list { if container.ID == containerId && container.Names[0] == "/container_delete_before_test" { pass = true break } } if pass == true { err = errors.New("container id found after remove test") panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) ContextCreate ¶
func (el *DockerSystem) ContextCreate()
ContextCreate (English): Create a background context
ContextCreate (Português): Cria um contexto background
func (*DockerSystem) DockerInfo ¶
func (el *DockerSystem) DockerInfo() (info types.Info, err error)
func (*DockerSystem) FileMakeAbsolutePath ¶
func (el *DockerSystem) FileMakeAbsolutePath( filePath string, ) ( fileAbsolutePath string, err error, )
FileMakeAbsolutePath (English): Make the relative file path absolute
filePath: string relative file path
FileMakeAbsolutePath (Português): Transforma o caminho relativo de arquivo em absoluto
filePath: caminho relativo do arquivo
func (*DockerSystem) FindDockerFile ¶
func (el *DockerSystem) FindDockerFile(folderPath string) (fullPathInsideTarFile string, err error)
FindDockerFile (English): Find dockerfile in folder tree.
Priority order: './Dockerfile-iotmaker', './Dockerfile', './dockerfile', 'Dockerfile.*', 'dockerfile.*', '.*Dockerfile.*', '.*dockerfile.*'
FindDockerFile (Português): Procura pelo arquivo dockerfile na árvore de diretórios.
Ordem de prioridade: './Dockerfile-iotmaker', './Dockerfile', './dockerfile', 'Dockerfile.*', 'dockerfile.*', '.*Dockerfile.*', '.*dockerfile.*'
func (DockerSystem) GetConfig ¶
func (el DockerSystem) GetConfig() (config *container.Config)
GetConfig
Return the container config pointer
func (*DockerSystem) ImageBuild ¶
func (el *DockerSystem) ImageBuild( dockerFileTarReader io.Reader, imageBuildOptions types.ImageBuildOptions, ) ( reader io.ReadCloser, err error, )
ImageBuild (English): Image build from reader. Please, see ImageBuildFromFolder(folderPath string, tags []string) and ImageBuildFromRemoteServer(server string, tags []string)
dockerFileTarReader: io.Reader reader from image imageBuildOptions: types.ImageBuildOptions image build options
ImageBuild (Português): Monta uma imagem baseada no header. Por favor, veja, ImageBuildFromFolder(folderPath string, tags []string) e ImageBuildFromRemoteServer(server string, tags []string)
dockerFileTarReader: io.Reader reader from image imageBuildOptions: types.ImageBuildOptions configurações da criação da imagem
func (*DockerSystem) ImageBuildFromFolder ¶
func (el *DockerSystem) ImageBuildFromFolder( folderPath string, imageName string, tags []string, imageBuildOptions types.ImageBuildOptions, channel chan ContainerPullStatusSendToChannel, ) ( imageID string, err error, )
ImageBuildFromFolder (English): Make a image from folder path content
folderPath: string absolute folder path tags: []string image tags channel: *chan channel of pull/build data Note: dockerfile priority order: './Dockerfile-iotmaker', './Dockerfile', './dockerfile', 'Dockerfile.*', 'dockerfile.*', '.*Dockerfile.*', '.*dockerfile.*'
ImageBuildFromFolder (Português): Monta uma imagem a partir de um diretório
folderPath: string caminho absoluto do diretório tags: []string tags da imagem channel: *chan channel com dados do pull/build da imagem Nota: ordem de prioridade do dockerfile: './Dockerfile-iotmaker', './Dockerfile', './dockerfile', 'Dockerfile.*', 'dockerfile.*', '.*Dockerfile.*', '.*dockerfile.*'
Example ¶
var err error var containerId string var imageId string var networkId string var dockerSys *DockerSystem var networkAutoConfiguration *NextNetworkAutoConfiguration var networkNextAddress *network.NetworkingConfig // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: 'static' folder path // Português: caminho da pasta 'static' var smallServerPathStatic string smallServerPathStatic = smallServerPath + string(os.PathSeparator) + "static" // English: 'index.html' file path // Português: caminho do arquivo 'index.html' var smallServerPathStaticContent string smallServerPathStaticContent = smallServerPathStatic + string(os.PathSeparator) + "index.html" // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: create a network named 'network_delete_before_test' // Português: cria uma nova rede de nome 'network_delete_before_test' networkId, networkAutoConfiguration, err = dockerSys.NetworkCreate( "network_delete_before_test", KNetworkDriveBridge, "local", "10.0.0.0/16", "10.0.0.1", ) if err != nil { panic(err) } if networkId == "" { err = errors.New("network id was not generated") panic(err) } // English: get next ip address from network, '10.0.0.2' // Português: pega o próxima endereço da rede, '10.0.0.2' _, networkNextAddress, err = networkAutoConfiguration.GetNext() if err != nil { panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: mount and start a container // Português: monta i inicializa o container containerId, err = dockerSys.ContainerCreateAndStart( // image name "image_server_delete_before_test:latest", // container name "container_delete_before_test", // restart policy KRestartPolicyUnlessStopped, // portMap nat.PortMap{ // container port number/protocol [tpc/udp] "3000/tcp": []nat.PortBinding{ // server original port { // server output port number HostPort: "9002", }, }, }, // mount volumes []mount.Mount{ { // bind - is the type for mounting host dir (real folder inside computer where // this code work) Type: KVolumeMountTypeBindString, // path inside host machine Source: smallServerPathStatic, // path inside image Target: "/static", }, }, // nil or container network configuration networkNextAddress, ) if err != nil { panic(err) } if containerId == "" { err = errors.New("container id was not generated") panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true var page []byte var found int var response *http.Response // English: contents of the static server index.html page // Português: conteúdo da página index.html do servidor estático var htmlIndexContent1 = []byte("<!DOCTYPE html><html><body><p>I'm alive!</p></body></html>") err = ioutil.WriteFile(smallServerPathStaticContent, htmlIndexContent1, os.ModePerm) if err != nil { panic(err) } // English: takes the content from the server for testing // Português: pega o conteúdo do servidor para teste response, err = http.Get("http://localhost:9002") if err != nil { panic(err) } page, err = ioutil.ReadAll(response.Body) if err != nil { panic(err) } // English: compare content // Português: compara o conteúdo found = bytes.Compare(page, htmlIndexContent1) if found == 1 { err = errors.New("small server content error") panic(err) } // English: contents of the static server index.html page // Português: conteúdo da página index.html do servidor estático htmlIndexContent1 = []byte("<!DOCTYPE html><html><body><p>I'm alive Dr. Frankenstein!</p></body></html>") err = ioutil.WriteFile(smallServerPathStaticContent, htmlIndexContent1, os.ModePerm) if err != nil { panic(err) } // English: takes the content from the server for testing // Português: pega o conteúdo do servidor para teste response, err = http.Get("http://localhost:9002") if err != nil { panic(err) } page, err = ioutil.ReadAll(response.Body) if err != nil { panic(err) } // English: compare content // Português: compara o conteúdo found = bytes.Compare(page, htmlIndexContent1) if found == 1 { err = errors.New("small server content error") panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) ImageBuildFromRemoteServer ¶
func (el *DockerSystem) ImageBuildFromRemoteServer( server, imageName string, tags []string, imageBuildOptions types.ImageBuildOptions, channel chan ContainerPullStatusSendToChannel, ) ( imageID string, err error, )
ImageBuildFromRemoteServer (English): Make a image from server content
server: Server path. Example: https://[<token>@]github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git imageName: image name. Example: server:lasted tags: image tags channel: channel of pull/build data Note: For get a github token settings > Developer settings > Personal access tokens > Generate new token Mark [x]repo - Full control of private repositories
ImageBuildFromRemoteServer (Português): Prepara uma imagem a partir do conteúdo de um servidor
server: Caminho do arquivo. Exemplo: https://[<token>@]github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git imageName: nome da imagem. Exemplo: server:lasted tags: tags da imagem channel: canal com dados de pull/build da imagem Note: Para usar um token do github settings > Developer settings > Personal access tokens > Generate new token Mark [x]repo - Full control of private repositories
func (DockerSystem) ImageBuildPrepareFolderContext ¶
func (el DockerSystem) ImageBuildPrepareFolderContext( dirPath string, ) ( file *bytes.Reader, err error, )
ImageBuildPrepareFolderContext (English): Read the directory and prepare a .tar file header, used on backup tapes. Note: This function was made public to allow purposeful changes to the generated file, such as making it possible to add a Dockerfile file, for example.
ImageBuildPrepareFolderContext (Português): Lê o diretório e prepara um header de arquivo .tar, usado em fitas de backup. Nota: Essa função foi deixada pública para permitir alterações propositais no arquivo gerado, como possibilitar adicionar um arquivo Dockerfile, por exemplo.
func (DockerSystem) ImageBuildPrepareFolderContextSupport ¶
func (*DockerSystem) ImageFindIdByName ¶
func (el *DockerSystem) ImageFindIdByName( name string, ) ( ID string, err error, )
ImageFindIdByName (English): Find image id by name
name: name of image
ImageFindIdByName (Português): Procura uma imagem por nome:
name: nome da imagem
Example ¶
var err error var dockerSys *DockerSystem var imageId string // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true var imageID string imageID, err = dockerSys.ImageFindIdByName("image_server_delete_before_test:latest") if err != nil { panic(err) } if imageID == "" { err = errors.New("image not found") panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) ImageFindIdByNameContains ¶
func (el *DockerSystem) ImageFindIdByNameContains( name string, ) ( list []NameAndId, err error, )
ImageFindIdByName (English): Find image whose part of the name contains the search term
name: search term
ImageFindIdByName (Português): Procura uma imagem cujo o nome contém o termo procurado
name: termo procurado
Example ¶
var err error var dockerSys *DockerSystem var imageId string // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true var pass = false var imageList []NameAndId imageList, err = dockerSys.ImageFindIdByNameContains("delete") if err != nil { panic(err) } for _, image := range imageList { if image.Name == "image_server_delete_before_test:latest" { pass = true break } } if pass == false { err = errors.New("image not found") panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) ImageGarbageCollector ¶
func (el *DockerSystem) ImageGarbageCollector() (err error)
ImageGarbageCollector (English): Remove temporary images, where first tag is "<none>:<none>"
ImageGarbageCollector (Português): Remove imagens temporárias, onde a primeira tag é "<none>:<none>"
Example ¶
var err error var dockerSys *DockerSystem var imageId string // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) ImageInspect ¶
func (el *DockerSystem) ImageInspect(id string) (inspect types.ImageInspect, err error)
ImageInspect (English): Inspect image by ID
ImageInspect (Português): Inspeciona a imagem por ID
func (*DockerSystem) ImageList ¶
func (el *DockerSystem) ImageList() ( list []types.ImageSummary, err error, )
ImageList (English): List all images inside host server
ImageList (Português): Lista todas as imagens do servidor hospedeiro
Example ¶
var err error var dockerSys *DockerSystem var imageId string // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true var pass = false var list []types.ImageSummary list, err = dockerSys.ImageList() if err != nil { panic(err) } for _, image := range list { if len(image.RepoTags) != 0 && image.RepoTags[0] == "image_server_delete_before_test:latest" { pass = true err = dockerSys.ImageRemove(image.ID, false, false) if err != nil { panic(err) } break } } if pass == false { err = errors.New("image not found") panic(err) } list, err = dockerSys.ImageList() if err != nil { panic(err) } for _, image := range list { if len(image.RepoTags) != 0 && image.RepoTags[0] == "image_server_delete_before_test:latest" { err = errors.New("image found after image removal") panic(err) } } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) ImageListExposedNatPort ¶
func (el *DockerSystem) ImageListExposedNatPort( imageId string, ) ( nat.PortMap, error, )
ImageListExposedNatPort (English): List all ports / protocols published inside image
name: image name
Note: Similar functions: ImageListExposedNatPort(), ImageListExposedPortsByName(), ImageListExposedPorts()
ImageListExposedNatPort (Português): Lista todas as portas / protocolos publicadas dentro da imagem
name: nome da imagem
Nota: funções similares: ImageListExposedNatPort(), ImageListExposedPortsByName(), ImageListExposedPorts()
Example ¶
var err error var dockerSys *DockerSystem var imageId string // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true var portList nat.PortMap portList, err = dockerSys.ImageListExposedNatPort(imageId) if err != nil { panic(err) } if len(portList) == 0 { err = errors.New("port list is empty") panic(err) } if len(portList["3000/tcp"]) == 0 { err = errors.New("3000/tcp port list is empty") panic(err) } if portList["3000/tcp"][0].HostPort != "3000/tcp" { err = errors.New("wrong output port at container port 3000/tcp") panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) ImageListExposedPorts ¶
func (el *DockerSystem) ImageListExposedPorts( id string, ) ( portList []nat.Port, err error, )
ImageListExposedPorts (English): List all ports / protocols published inside image
id: image ID
Note: Similar functions: ImageListExposedNatPort(), ImageListExposedPortsByName(), ImageListExposedPorts()
ImageListExposedPorts (Português): Lista todas as portas / protocolos publicadas dentro da imagem
id: ID da imagem
Nota: funções similares: ImageListExposedNatPort(), ImageListExposedPortsByName(), ImageListExposedPorts()
Example ¶
var err error var dockerSys *DockerSystem var imageId string // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true var portList []nat.Port portList, err = dockerSys.ImageListExposedPorts(imageId) if err != nil { panic(err) } if len(portList) == 0 { err = errors.New("port list is empty") panic(err) } if portList[0].Port() != "3000" { err = errors.New("wrong server port") panic(err) } if portList[0].Proto() != "tcp" { err = errors.New("wrong server port") panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) ImageListExposedPortsByName ¶
func (el *DockerSystem) ImageListExposedPortsByName( name string, ) ( portList []nat.Port, err error, )
ImageListExposedPortsByName (English): List all ports / protocols published inside image by image name
name: image name
Note: Similar functions: ImageListExposedNatPort(), ImageListExposedPortsByName(), ImageListExposedPorts()
ImageListExposedPortsByName (Português): Lista todas as portas / protocolos publicadas dentro da imagem pelo nome da imagem
name: nome da imagem
Nota: funções similares: ImageListExposedNatPort(), ImageListExposedPortsByName(), ImageListExposedPorts()
Example ¶
var err error var dockerSys *DockerSystem var imageId string // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true var portList []nat.Port portList, err = dockerSys.ImageListExposedPortsByName("image_server_delete_before_test:latest") if err != nil { panic(err) } if len(portList) == 0 { err = errors.New("port list is empty") panic(err) } if portList[0].Port() != "3000" { err = errors.New("wrong server port") panic(err) } if portList[0].Proto() != "tcp" { err = errors.New("wrong server port") panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) ImageListExposedVolumes ¶
func (el *DockerSystem) ImageListExposedVolumes( id string, ) ( list []string, err error, )
ImageListExposedVolumes (English): List all volumes exposed inside image file (dockerfile)
id: image ID
ImageListExposedVolumes (Português): Lista todos os volumes expostos pela imagem (dockerfile)
id: ID da imagem
Example ¶
var err error var dockerSys *DockerSystem var imageId string // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true var volumesList []string volumesList, err = dockerSys.ImageListExposedVolumes(imageId) if err != nil { panic(err) } if len(volumesList) == 0 { err = errors.New("volumes list is empty") panic(err) } if volumesList[0] != "/static" { err = errors.New("wrong volume in volumes list") panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) ImageListExposedVolumesByName ¶
func (el *DockerSystem) ImageListExposedVolumesByName( name string, ) ( list []string, err error, )
ImageListExposedVolumesByName (English): List all volumes exposed inside image file (dockerfile) by image name
name: name of image
ImageListExposedVolumesByName (Português): Lista todos os volumes expostos pela imagem (dockerfile) pelo nome da imagem
name: nome da imagem
Example ¶
var err error var dockerSys *DockerSystem var imageId string // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true var volumesList []string volumesList, err = dockerSys.ImageListExposedVolumesByName("image_server_delete_before_test:latest") if err != nil { panic(err) } if len(volumesList) == 0 { err = errors.New("volumes list is empty") panic(err) } if volumesList[0] != "/static" { err = errors.New("wrong volume in volumes list") panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) ImageMountNatPortListChangeExposed ¶
func (el *DockerSystem) ImageMountNatPortListChangeExposed( imageId string, currentPortList, changeToPortList []nat.Port, ) ( nat.PortMap, error, )
fixme: isto deveria ser privado?
func (*DockerSystem) ImageMountNatPortListChangeExposedWithIpAddress ¶
func (el *DockerSystem) ImageMountNatPortListChangeExposedWithIpAddress( imageId, ipAddress string, currentPortList, changeToPortList []nat.Port, ) ( nat.PortMap, error, )
fixme: isto deveria ser privado?
func (*DockerSystem) ImagePull ¶
func (el *DockerSystem) ImagePull( name string, channel chan ContainerPullStatusSendToChannel, ) ( imageId string, imageName string, err error, )
Example ¶
var err error var dockerSys *DockerSystem var imageId string var imageName string // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { //fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo //return } } } }(chStatus, chProcessEnd) // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } imageId, imageName, err = dockerSys.ImagePull( "alpine:latest", chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } if imageName != "alpine:latest" { err = errors.New("wrong image name") panic(err) } err = dockerSys.ImageRemove(imageId, false, false) if err != nil { panic(err) } imageId, err = dockerSys.ImageFindIdByName("alpine:latest") if err == nil || err.Error() != "image name not found" { err = errors.New("image removal error") panic(err) } if imageId != "" { err = errors.New("image removal error") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) ImageRemove ¶
func (el *DockerSystem) ImageRemove( id string, force, pruneChildren bool, ) ( err error, )
Example ¶
var err error var dockerSys *DockerSystem var imageId string var imageName string // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { //fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo //return } } } }(chStatus, chProcessEnd) // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } imageId, imageName, err = dockerSys.ImagePull( "alpine:latest", chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } if imageName != "alpine:latest" { err = errors.New("wrong image name") panic(err) } err = dockerSys.ImageRemove(imageId, false, false) if err != nil { panic(err) } imageId, err = dockerSys.ImageFindIdByName("alpine:latest") if err == nil || err.Error() != "image name not found" { err = errors.New("image removal error") panic(err) } if imageId != "" { err = errors.New("image removal error") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) ImageRemoveByName ¶
func (el *DockerSystem) ImageRemoveByName( name string, force, pruneChildren bool, ) ( err error, )
Example ¶
var err error var dockerSys *DockerSystem var imageId string var imageName string // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { //fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo //return } } } }(chStatus, chProcessEnd) // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } imageId, imageName, err = dockerSys.ImagePull( "alpine:latest", chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } if imageName != "alpine:latest" { err = errors.New("wrong image name") panic(err) } err = dockerSys.ImageRemoveByName("alpine:latest", false, false) if err != nil { panic(err) } imageId, err = dockerSys.ImageFindIdByName("alpine:latest") if err == nil || err.Error() != "image name not found" { err = errors.New("image removal error") panic(err) } if imageId != "" { err = errors.New("image removal error") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) ImageVerifyVolume ¶
func (el *DockerSystem) ImageVerifyVolume( id, path string, ) ( bool, error, )
verify if exposed volume (folder only) defined by user is exposed in image
func (*DockerSystem) NetworkConnect ¶
func (el *DockerSystem) NetworkConnect( networkID, containerID string, config *network.EndpointSettings, ) ( err error, )
Example ¶
var err error var containerId string var imageId string var networkId string var dockerSys *DockerSystem // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: 'static' folder path // Português: caminho da pasta 'static' var smallServerPathStatic string smallServerPathStatic = smallServerPath + string(os.PathSeparator) + "static" // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: create a network named 'network_delete_before_test' // Português: cria uma nova rede de nome 'network_delete_before_test' networkId, _, err = dockerSys.NetworkCreate( "network_delete_before_test", KNetworkDriveBridge, "local", "10.0.0.0/16", "10.0.0.1", ) if err != nil { panic(err) } if networkId == "" { err = errors.New("network id was not generated") panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: mount and start a container // Português: monta i inicializa o container containerId, err = dockerSys.ContainerCreate( // image name "image_server_delete_before_test:latest", // container name "container_delete_before_test", // restart policy KRestartPolicyUnlessStopped, // portMap nat.PortMap{ // container port number/protocol [tpc/udp] "3000/tcp": []nat.PortBinding{ // server original port { // server output port number HostPort: "9002", }, }, }, // mount volumes []mount.Mount{ { // bind - is the type for mounting host dir (real folder inside computer where // this code work) Type: KVolumeMountTypeBindString, // path inside host machine Source: smallServerPathStatic, // path inside image Target: "/static", }, }, // nil or container network configuration nil, ) if err != nil { panic(err) } if containerId == "" { err = errors.New("container id was not generated") panic(err) } err = dockerSys.NetworkConnect(networkId, containerId, nil) if err != nil { panic(err) } // English: container start // Português: inicia o container err = dockerSys.ContainerStart(containerId) if err != nil { panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true // English: inspect a container by id // Português: inspeciona um container por id var inspect types.ContainerJSON inspect, err = dockerSys.ContainerInspect(containerId) if err != nil { panic(err) } if inspect.Name != "/container_delete_before_test" { err = errors.New("wrong container name") panic(err) } if inspect.State == nil { err = errors.New("container not running") panic(err) } if inspect.State.Running == false { err = errors.New("container not running") panic(err) } if len(inspect.Config.ExposedPorts) == 0 { err = errors.New("container not running") panic(err) } if reflect.ValueOf(inspect.Config.ExposedPorts["3000/tcp"]).IsZero() == false { err = errors.New("exposed ports fail") panic(err) } if inspect.NetworkSettings.Networks["network_delete_before_test"].IPAddress != "10.0.0.2" { err = errors.New("IPv4 address error") panic(err) } err = dockerSys.ContainerStop(containerId) if err != nil { panic(err) } err = dockerSys.NetworkDisconnect(networkId, containerId, false) if err != nil { panic(err) } err = dockerSys.NetworkRemove(networkId) if err != nil { panic(err) } networkId, err = dockerSys.NetworkFindIdByName("bridge") if err != nil { panic(err) } err = dockerSys.NetworkConnect(networkId, containerId, nil) if err != nil { panic(err) } // English: container start // Português: inicia o container err = dockerSys.ContainerStart(containerId) if err != nil { panic(err) } // English: inspect a container by id // Português: inspeciona um container por id inspect, err = dockerSys.ContainerInspect(containerId) if err != nil { panic(err) } if inspect.Name != "/container_delete_before_test" { err = errors.New("wrong container name") panic(err) } if inspect.State == nil { err = errors.New("container not running") panic(err) } if inspect.State.Running == false { err = errors.New("container not running") panic(err) } if reflect.ValueOf(inspect.Config.ExposedPorts["3000/tcp"]).IsZero() == false { err = errors.New("exposed ports fail") panic(err) } if inspect.NetworkSettings.Networks["bridge"].IPAddress == "10.0.0.2" { err = errors.New("IPv4 address error") panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) NetworkCreate ¶
func (el *DockerSystem) NetworkCreate( name string, drive NetworkDrive, scope, subnet, gateway string, ) ( id string, networkGenerator *NextNetworkAutoConfiguration, err error, )
NetworkCreate create network
name: string Ex.: containerNetwork drive: NetworkDrive Ex.: KNetworkDriveBridge scope: string Ex.: local subnet: string Ex.: 10.0.0.0/16 (note: use base 10) gateway: string Ex.: 10.0.0.1 (note: use base 10)
Example ¶
var err error var containerId string var imageId string var networkId string var dockerSys *DockerSystem var networkAutoConfiguration *NextNetworkAutoConfiguration var networkNextAddress *network.NetworkingConfig // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: 'static' folder path // Português: caminho da pasta 'static' var smallServerPathStatic string smallServerPathStatic = smallServerPath + string(os.PathSeparator) + "static" // English: 'index.html' file path // Português: caminho do arquivo 'index.html' var smallServerPathStaticContent string smallServerPathStaticContent = smallServerPathStatic + string(os.PathSeparator) + "index.html" // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: create a network named 'network_delete_before_test' // Português: cria uma nova rede de nome 'network_delete_before_test' networkId, networkAutoConfiguration, err = dockerSys.NetworkCreate( "network_delete_before_test", KNetworkDriveBridge, "local", "10.0.0.0/16", "10.0.0.1", ) if err != nil { panic(err) } if networkId == "" { err = errors.New("network id was not generated") panic(err) } // English: get next ip address from network, '10.0.0.2' // Português: pega o próxima endereço da rede, '10.0.0.2' _, networkNextAddress, err = networkAutoConfiguration.GetNext() if err != nil { panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: mount and start a container // Português: monta i inicializa o container containerId, err = dockerSys.ContainerCreateAndStart( // image name "image_server_delete_before_test:latest", // container name "container_delete_before_test", // restart policy KRestartPolicyUnlessStopped, // portMap nat.PortMap{ // container port number/protocol [tpc/udp] "3000/tcp": []nat.PortBinding{ // server original port { // server output port number HostPort: "9002", }, }, }, // mount volumes []mount.Mount{ { // bind - is the type for mounting host dir (real folder inside computer where // this code work) Type: KVolumeMountTypeBindString, // path inside host machine Source: smallServerPathStatic, // path inside image Target: "/static", }, }, // nil or container network configuration networkNextAddress, ) if err != nil { panic(err) } if containerId == "" { err = errors.New("container id was not generated") panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true var page []byte var found int var response *http.Response // English: contents of the static server index.html page // Português: conteúdo da página index.html do servidor estático var htmlIndexContent1 = []byte("<!DOCTYPE html><html><body><p>I'm alive!</p></body></html>") err = ioutil.WriteFile(smallServerPathStaticContent, htmlIndexContent1, os.ModePerm) if err != nil { panic(err) } // English: takes the content from the server for testing // Português: pega o conteúdo do servidor para teste response, err = http.Get("http://localhost:9002") if err != nil { panic(err) } page, err = ioutil.ReadAll(response.Body) if err != nil { panic(err) } // English: compare content // Português: compara o conteúdo found = bytes.Compare(page, htmlIndexContent1) if found == 1 { err = errors.New("small server content error") panic(err) } // English: contents of the static server index.html page // Português: conteúdo da página index.html do servidor estático htmlIndexContent1 = []byte("<!DOCTYPE html><html><body><p>I'm alive Dr. Frankenstein!</p></body></html>") err = ioutil.WriteFile(smallServerPathStaticContent, htmlIndexContent1, os.ModePerm) if err != nil { panic(err) } // English: takes the content from the server for testing // Português: pega o conteúdo do servidor para teste response, err = http.Get("http://localhost:9002") if err != nil { panic(err) } page, err = ioutil.ReadAll(response.Body) if err != nil { panic(err) } // English: compare content // Português: compara o conteúdo found = bytes.Compare(page, htmlIndexContent1) if found == 1 { err = errors.New("small server content error") panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) NetworkDisconnect ¶
func (el *DockerSystem) NetworkDisconnect( networkID, containerID string, force bool, ) ( err error, )
Example ¶
var err error var containerId string var imageId string var networkId string var dockerSys *DockerSystem // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: 'static' folder path // Português: caminho da pasta 'static' var smallServerPathStatic string smallServerPathStatic = smallServerPath + string(os.PathSeparator) + "static" // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: create a network named 'network_delete_before_test' // Português: cria uma nova rede de nome 'network_delete_before_test' networkId, _, err = dockerSys.NetworkCreate( "network_delete_before_test", KNetworkDriveBridge, "local", "10.0.0.0/16", "10.0.0.1", ) if err != nil { panic(err) } if networkId == "" { err = errors.New("network id was not generated") panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: mount and start a container // Português: monta i inicializa o container containerId, err = dockerSys.ContainerCreate( // image name "image_server_delete_before_test:latest", // container name "container_delete_before_test", // restart policy KRestartPolicyUnlessStopped, // portMap nat.PortMap{ // container port number/protocol [tpc/udp] "3000/tcp": []nat.PortBinding{ // server original port { // server output port number HostPort: "9002", }, }, }, // mount volumes []mount.Mount{ { // bind - is the type for mounting host dir (real folder inside computer where // this code work) Type: KVolumeMountTypeBindString, // path inside host machine Source: smallServerPathStatic, // path inside image Target: "/static", }, }, // nil or container network configuration nil, ) if err != nil { panic(err) } if containerId == "" { err = errors.New("container id was not generated") panic(err) } err = dockerSys.NetworkConnect(networkId, containerId, nil) if err != nil { panic(err) } // English: container start // Português: inicia o container err = dockerSys.ContainerStart(containerId) if err != nil { panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true // English: inspect a container by id // Português: inspeciona um container por id var inspect types.ContainerJSON inspect, err = dockerSys.ContainerInspect(containerId) if err != nil { panic(err) } if inspect.Name != "/container_delete_before_test" { err = errors.New("wrong container name") panic(err) } if inspect.State == nil { err = errors.New("container not running") panic(err) } if inspect.State.Running == false { err = errors.New("container not running") panic(err) } if len(inspect.Config.ExposedPorts) == 0 { err = errors.New("container not running") panic(err) } if reflect.ValueOf(inspect.Config.ExposedPorts["3000/tcp"]).IsZero() == false { err = errors.New("exposed ports fail") panic(err) } if inspect.NetworkSettings.Networks["network_delete_before_test"].IPAddress != "10.0.0.2" { err = errors.New("IPv4 address error") panic(err) } err = dockerSys.ContainerStop(containerId) if err != nil { panic(err) } err = dockerSys.NetworkDisconnect(networkId, containerId, false) if err != nil { panic(err) } err = dockerSys.NetworkRemove(networkId) if err != nil { panic(err) } networkId, err = dockerSys.NetworkFindIdByName("bridge") if err != nil { panic(err) } err = dockerSys.NetworkConnect(networkId, containerId, nil) if err != nil { panic(err) } // English: container start // Português: inicia o container err = dockerSys.ContainerStart(containerId) if err != nil { panic(err) } // English: inspect a container by id // Português: inspeciona um container por id inspect, err = dockerSys.ContainerInspect(containerId) if err != nil { panic(err) } if inspect.Name != "/container_delete_before_test" { err = errors.New("wrong container name") panic(err) } if inspect.State == nil { err = errors.New("container not running") panic(err) } if inspect.State.Running == false { err = errors.New("container not running") panic(err) } if reflect.ValueOf(inspect.Config.ExposedPorts["3000/tcp"]).IsZero() == false { err = errors.New("exposed ports fail") panic(err) } if inspect.NetworkSettings.Networks["bridge"].IPAddress == "10.0.0.2" { err = errors.New("IPv4 address error") panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) NetworkFindIdByName ¶
func (el *DockerSystem) NetworkFindIdByName( name string, ) ( id string, err error, )
Example ¶
var err error var containerId string var imageId string var networkId string var dockerSys *DockerSystem // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: 'static' folder path // Português: caminho da pasta 'static' var smallServerPathStatic string smallServerPathStatic = smallServerPath + string(os.PathSeparator) + "static" // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: create a network named 'network_delete_before_test' // Português: cria uma nova rede de nome 'network_delete_before_test' networkId, _, err = dockerSys.NetworkCreate( "network_delete_before_test", KNetworkDriveBridge, "local", "10.0.0.0/16", "10.0.0.1", ) if err != nil { panic(err) } if networkId == "" { err = errors.New("network id was not generated") panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: mount and start a container // Português: monta i inicializa o container containerId, err = dockerSys.ContainerCreate( // image name "image_server_delete_before_test:latest", // container name "container_delete_before_test", // restart policy KRestartPolicyUnlessStopped, // portMap nat.PortMap{ // container port number/protocol [tpc/udp] "3000/tcp": []nat.PortBinding{ // server original port { // server output port number HostPort: "9002", }, }, }, // mount volumes []mount.Mount{ { // bind - is the type for mounting host dir (real folder inside computer where // this code work) Type: KVolumeMountTypeBindString, // path inside host machine Source: smallServerPathStatic, // path inside image Target: "/static", }, }, // nil or container network configuration nil, ) if err != nil { panic(err) } if containerId == "" { err = errors.New("container id was not generated") panic(err) } err = dockerSys.NetworkConnect(networkId, containerId, nil) if err != nil { panic(err) } // English: container start // Português: inicia o container err = dockerSys.ContainerStart(containerId) if err != nil { panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true // English: inspect a container by id // Português: inspeciona um container por id var inspect types.ContainerJSON inspect, err = dockerSys.ContainerInspect(containerId) if err != nil { panic(err) } if inspect.Name != "/container_delete_before_test" { err = errors.New("wrong container name") panic(err) } if inspect.State == nil { err = errors.New("container not running") panic(err) } if inspect.State.Running == false { err = errors.New("container not running") panic(err) } if len(inspect.Config.ExposedPorts) == 0 { err = errors.New("container not running") panic(err) } if reflect.ValueOf(inspect.Config.ExposedPorts["3000/tcp"]).IsZero() == false { err = errors.New("exposed ports fail") panic(err) } if inspect.NetworkSettings.Networks["network_delete_before_test"].IPAddress != "10.0.0.2" { err = errors.New("IPv4 address error") panic(err) } err = dockerSys.ContainerStop(containerId) if err != nil { panic(err) } err = dockerSys.NetworkDisconnect(networkId, containerId, false) if err != nil { panic(err) } err = dockerSys.NetworkRemove(networkId) if err != nil { panic(err) } networkId, err = dockerSys.NetworkFindIdByName("bridge") if err != nil { panic(err) } err = dockerSys.NetworkConnect(networkId, containerId, nil) if err != nil { panic(err) } // English: container start // Português: inicia o container err = dockerSys.ContainerStart(containerId) if err != nil { panic(err) } // English: inspect a container by id // Português: inspeciona um container por id inspect, err = dockerSys.ContainerInspect(containerId) if err != nil { panic(err) } if inspect.Name != "/container_delete_before_test" { err = errors.New("wrong container name") panic(err) } if inspect.State == nil { err = errors.New("container not running") panic(err) } if inspect.State.Running == false { err = errors.New("container not running") panic(err) } if reflect.ValueOf(inspect.Config.ExposedPorts["3000/tcp"]).IsZero() == false { err = errors.New("exposed ports fail") panic(err) } if inspect.NetworkSettings.Networks["bridge"].IPAddress == "10.0.0.2" { err = errors.New("IPv4 address error") panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) NetworkFindIdByNameContains ¶
func (el *DockerSystem) NetworkFindIdByNameContains( name string, ) ( list []NameAndId, err error, )
Example ¶
var err error var networkId string var dockerSys *DockerSystem // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: create a network named 'network_delete_before_test' // Português: cria uma nova rede de nome 'network_delete_before_test' networkId, _, err = dockerSys.NetworkCreate( "network_delete_before_test", KNetworkDriveBridge, "local", "10.0.0.0/16", "10.0.0.1", ) if err != nil { panic(err) } if networkId == "" { err = errors.New("network id was not generated") panic(err) } var list []NameAndId list, err = dockerSys.NetworkFindIdByNameContains("delete") if err != nil { panic(err) } for _, networkData := range list { err = dockerSys.NetworkRemove(networkData.ID) if err != nil { panic(err) } } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) NetworkFindNetworkTypeBridgePublic ¶
func (el *DockerSystem) NetworkFindNetworkTypeBridgePublic() ( inspect types.NetworkResource, err error, )
func (*DockerSystem) NetworkGetGenerator ¶
func (el *DockerSystem) NetworkGetGenerator( name string, ) ( configuration *NextNetworkAutoConfiguration, )
func (*DockerSystem) NetworkInspect ¶
func (el *DockerSystem) NetworkInspect( id string, ) ( inspect types.NetworkResource, err error, )
Example ¶
var err error var networkId string var dockerSys *DockerSystem // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: create a network named 'network_delete_before_test' // Português: cria uma nova rede de nome 'network_delete_before_test' networkId, _, err = dockerSys.NetworkCreate( "network_delete_before_test", KNetworkDriveBridge, "local", "10.0.0.0/16", "10.0.0.1", ) if err != nil { panic(err) } if networkId == "" { err = errors.New("network id was not generated") panic(err) } var inspect types.NetworkResource inspect, err = dockerSys.NetworkInspect(networkId) if err != nil { panic(err) } if inspect.ID != networkId { err = errors.New("wrong network id") panic(err) } if inspect.Name != "network_delete_before_test" { err = errors.New("wrong network name") panic(err) } if len(inspect.IPAM.Config) == 0 { err = errors.New("wrong network config") panic(err) } if inspect.IPAM.Config[0].Gateway != "10.0.0.1" { err = errors.New("wrong network name") panic(err) } if inspect.IPAM.Config[0].Subnet != "10.0.0.0/16" { err = errors.New("wrong network name") panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) NetworkList ¶
func (el *DockerSystem) NetworkList() ( netList []types.NetworkResource, err error, )
Example ¶
var err error var networkId string var dockerSys *DockerSystem // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: create a network named 'network_delete_before_test' // Português: cria uma nova rede de nome 'network_delete_before_test' networkId, _, err = dockerSys.NetworkCreate( "network_delete_before_test", KNetworkDriveBridge, "local", "10.0.0.0/16", "10.0.0.1", ) if err != nil { panic(err) } if networkId == "" { err = errors.New("network id was not generated") panic(err) } var list []types.NetworkResource list, err = dockerSys.NetworkList() if err != nil { panic(err) } var pass = false for _, networkData := range list { if networkData.ID == networkId { pass = true break } } if pass == false { err = errors.New("network network_delete_before_test not found") panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) NetworkListLocalCreated ¶
func (el *DockerSystem) NetworkListLocalCreated() ( list map[string]string, )
func (*DockerSystem) NetworkRemove ¶
func (el *DockerSystem) NetworkRemove( id string, ) ( err error, )
Example ¶
var err error var networkId string var dockerSys *DockerSystem // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: create a network named 'network_delete_before_test' // Português: cria uma nova rede de nome 'network_delete_before_test' networkId, _, err = dockerSys.NetworkCreate( "network_delete_before_test", KNetworkDriveBridge, "local", "10.0.0.0/16", "10.0.0.1", ) if err != nil { panic(err) } if networkId == "" { err = errors.New("network id was not generated") panic(err) } var networkFound bool networkFound, err = dockerSys.NetworkVerifyName("network_delete_before_test") if err != nil { panic(err) } if networkFound == false { err = errors.New("network network_delete_before_test not found") panic(err) } err = dockerSys.NetworkRemove(networkId) if err != nil { panic(err) } networkFound, err = dockerSys.NetworkVerifyName("network_delete_before_test") if err != nil { panic(err) } if networkFound == true { err = errors.New("network removal erro") panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) NetworkRemoveByName ¶
func (el *DockerSystem) NetworkRemoveByName( name string, ) ( err error, )
Example ¶
var err error var networkId string var dockerSys *DockerSystem // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: create a network named 'network_delete_before_test' // Português: cria uma nova rede de nome 'network_delete_before_test' networkId, _, err = dockerSys.NetworkCreate( "network_delete_before_test", KNetworkDriveBridge, "local", "10.0.0.0/16", "10.0.0.1", ) if err != nil { panic(err) } if networkId == "" { err = errors.New("network id was not generated") panic(err) } var networkFound bool networkFound, err = dockerSys.NetworkVerifyName("network_delete_before_test") if err != nil { panic(err) } if networkFound == false { err = errors.New("network network_delete_before_test not found") panic(err) } err = dockerSys.NetworkRemoveByName("network_delete_before_test") if err != nil { panic(err) } networkFound, err = dockerSys.NetworkVerifyName("network_delete_before_test") if err != nil { panic(err) } if networkFound == true { err = errors.New("network removal erro") panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) NetworkVerifyName ¶
func (el *DockerSystem) NetworkVerifyName( name string, ) ( exists bool, err error, )
verify if network name exists
Example ¶
var err error var networkId string var dockerSys *DockerSystem // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: create a network named 'network_delete_before_test' // Português: cria uma nova rede de nome 'network_delete_before_test' networkId, _, err = dockerSys.NetworkCreate( "network_delete_before_test", KNetworkDriveBridge, "local", "10.0.0.0/16", "10.0.0.1", ) if err != nil { panic(err) } if networkId == "" { err = errors.New("network id was not generated") panic(err) } var networkFound bool networkFound, err = dockerSys.NetworkVerifyName("network_delete_before_test") if err != nil { panic(err) } if networkFound == false { err = errors.New("network network_delete_before_test not found") panic(err) } err = dockerSys.NetworkRemove(networkId) if err != nil { panic(err) } networkFound, err = dockerSys.NetworkVerifyName("network_delete_before_test") if err != nil { panic(err) } if networkFound == true { err = errors.New("network removal erro") panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (DockerSystem) RemoveAllByNameContains ¶
func (el DockerSystem) RemoveAllByNameContains(name string) (err error)
RemoveAllByNameContains remove trash after test. This function removes container, image and network by name, and unlinked volumes and imagens
Example ¶
var err error var networkId string var dockerSys *DockerSystem // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: create a network named 'network_delete_before_test' // Português: cria uma nova rede de nome 'network_delete_before_test' networkId, _, err = dockerSys.NetworkCreate( "network_delete_before_test", KNetworkDriveBridge, "local", "10.0.0.0/16", "10.0.0.1", ) if err != nil { panic(err) } if networkId == "" { err = errors.New("network id was not generated") panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } _, err = dockerSys.NetworkFindIdByName("network_delete_before_test") if err == nil { err = errors.New("network don't deleted") panic(err) } if err.Error() != "network not found" { panic(err) }
Output:
func (*DockerSystem) SetHealthcheck ¶
func (el *DockerSystem) SetHealthcheck(healthcheck HealthConfig)
SetHealthcheck (English): The HEALTHCHECK instruction has two forms:
HEALTHCHECK [OPTIONS] CMD command (check container health by running a command inside the container) HEALTHCHECK NONE (disable any healthcheck inherited from the base image)
The HEALTHCHECK instruction tells Docker how to test a container to check that it is still working. This can detect cases such as a web server that is stuck in an infinite loop and unable to handle new connections, even though the server process is still running.
When a container has a healthcheck specified, it has a health status in addition to its normal status. This status is initially starting. Whenever a health check passes, it becomes healthy (whatever state it was previously in). After a certain number of consecutive failures, it becomes unhealthy.
The options that can appear before CMD are:
--interval=DURATION (default: 30s) --timeout=DURATION (default: 30s) --start-period=DURATION (default: 0s) --retries=N (default: 3)
The health check will first run interval seconds after the container is started, and then again interval seconds after each previous check completes.
If a single run of the check takes longer than timeout seconds then the check is considered to have failed.
It takes retries consecutive failures of the health check for the container to be considered unhealthy.
start period provides initialization time for containers that need time to bootstrap. Probe failure during that period will not be counted towards the maximum number of retries. However, if a health check succeeds during the start period, the container is considered started and all consecutive failures will be counted towards the maximum number of retries.
There can only be one HEALTHCHECK instruction in a Dockerfile. If you list more than one then only the last HEALTHCHECK will take effect.
The command after the CMD keyword can be either a shell command (e.g. HEALTHCHECK CMD /bin/check-running) or an exec array (as with other Dockerfile commands; see e.g. ENTRYPOINT for details).
The command’s exit status indicates the health status of the container. The possible values are:
0: success - the container is healthy and ready for use 1: unhealthy - the container is not working correctly 2: reserved - do not use this exit code
For example, to check every five minutes or so that a web-server is able to serve the site’s main page within three seconds:
HEALTHCHECK --interval=5m --timeout=3s \ CMD curl -f http://localhost/ || exit 1
To help debug failing probes, any output text (UTF-8 encoded) that the command writes on stdout or stderr will be stored in the health status and can be queried with docker inspect. Such output should be kept short (only the first 4096 bytes are stored currently).
When the health status of a container changes, a health_status event is generated with the new status.
https://docs.docker.com/engine/reference/builder/#healthcheck
func (*DockerSystem) SetOnBuild ¶
func (el *DockerSystem) SetOnBuild(onBuild []string)
SetOnBuild (English): The ONBUILD instruction adds to the image a trigger instruction to be executed at a later time, when the image is used as the base for another build. The trigger will be executed in the context of the downstream build, as if it had been inserted immediately after the FROM instruction in the downstream Dockerfile.
Any build instruction can be registered as a trigger.
This is useful if you are building an image which will be used as a base to build other images, for example an application build environment or a daemon which may be customized with user-specific configuration.
For example, if your image is a reusable Python application builder, it will require application source code to be added in a particular directory, and it might require a build script to be called after that. You can’t just call ADD and RUN now, because you don’t yet have access to the application source code, and it will be different for each application build. You could simply provide application developers with a boilerplate Dockerfile to copy-paste into their application, but that is inefficient, error-prone and difficult to update because it mixes with application-specific code.
The solution is to use ONBUILD to register advance instructions to run later, during the next build stage.
Here’s how it works:
When it encounters an ONBUILD instruction, the builder adds a trigger to the metadata of the image being built. The instruction does not otherwise affect the current build. At the end of the build, a list of all triggers is stored in the image manifest, under the key OnBuild. They can be inspected with the docker inspect command. Later the image may be used as a base for a new build, using the FROM instruction. As part of processing the FROM instruction, the downstream builder looks for ONBUILD triggers, and executes them in the same order they were registered. If any of the triggers fail, the FROM instruction is aborted which in turn causes the build to fail. If all triggers succeed, the FROM instruction completes and the build continues as usual. Triggers are cleared from the final image after being executed. In other words they are not inherited by “grand-children” builds. For example you might add something like this:
ONBUILD ADD . /app/src ONBUILD RUN /usr/local/bin/python-build --dir /app/src
Warning: Chaining ONBUILD instructions using ONBUILD ONBUILD isn’t allowed. Warning: The ONBUILD instruction may not trigger FROM or MAINTAINER instructions.
func (*DockerSystem) VolumeCreate ¶
func (*DockerSystem) VolumeFindByName ¶
func (el *DockerSystem) VolumeFindByName( name string, ) ( volume types.Volume, err error, )
Example ¶
var err error var containerId string var imageId string var dockerSys *DockerSystem // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: mount and start a container // Português: monta i inicializa o container containerId, err = dockerSys.ContainerCreate( // image name "image_server_delete_before_test:latest", // container name "container_delete_before_test", // restart policy KRestartPolicyUnlessStopped, // portMap nat.PortMap{ // container port number/protocol [tpc/udp] "3000/tcp": []nat.PortBinding{ // server original port { // server output port number HostPort: "9002", }, }, }, // mount volumes []mount.Mount{ { // bind - is the type for mounting host dir (real folder inside computer where // this code work) Type: KVolumeMountTypeVolumeString, // path inside host machine Source: "static_smallServer", // path inside image Target: "/static", }, }, // nil or container network configuration nil, ) if err != nil { panic(err) } if containerId == "" { err = errors.New("container id was not generated") panic(err) } // English: container start // Português: inicia o container err = dockerSys.ContainerStart(containerId) if err != nil { panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true var volume types.Volume volume, err = dockerSys.VolumeFindByName("static_smallServer") if err != nil { panic(err) } if volume.Name != "static_smallServer" { err = errors.New("volume name not found") panic(err) } if volume.Driver != "local" { err = errors.New("wrong volume drive") panic(err) } if volume.Scope != "local" { err = errors.New("wrong volume scope") panic(err) } err = dockerSys.ContainerStopAndRemove(containerId) if err != nil { panic(err) } err = dockerSys.VolumeRemove("static_smallServer") if err != nil { panic(err) } volume, err = dockerSys.VolumeFindByName("static_smallServer") if err != nil && err.Error() != "volume name not found" { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) VolumeInspect ¶
func (el *DockerSystem) VolumeInspect( ID string, ) ( inspect types.Volume, err error, )
func (*DockerSystem) VolumeList ¶
func (el *DockerSystem) VolumeList() ( volList []types.Volume, err error, )
Example ¶
var err error var containerId string var imageId string var dockerSys *DockerSystem // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: mount and start a container // Português: monta i inicializa o container containerId, err = dockerSys.ContainerCreate( // image name "image_server_delete_before_test:latest", // container name "container_delete_before_test", // restart policy KRestartPolicyUnlessStopped, // portMap nat.PortMap{ // container port number/protocol [tpc/udp] "3000/tcp": []nat.PortBinding{ // server original port { // server output port number HostPort: "9002", }, }, }, // mount volumes []mount.Mount{ { // bind - is the type for mounting host dir (real folder inside computer where // this code work) Type: KVolumeMountTypeVolumeString, // path inside host machine Source: "static_smallServer", // path inside image Target: "/static", }, }, // nil or container network configuration nil, ) if err != nil { panic(err) } if containerId == "" { err = errors.New("container id was not generated") panic(err) } // English: container start // Português: inicia o container err = dockerSys.ContainerStart(containerId) if err != nil { panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true var pass = false var volumeList []types.Volume volumeList, err = dockerSys.VolumeList() if err != nil { panic(err) } for _, volumeData := range volumeList { if volumeData.Name == "static_smallServer" { pass = true break } } if pass == false { err = errors.New("volume name static_smallServer not found") panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (*DockerSystem) VolumeRemove ¶
func (el *DockerSystem) VolumeRemove( name string, ) ( err error, )
Example ¶
var err error var containerId string var imageId string var dockerSys *DockerSystem // English: make a channel to end goroutine // Português: monta um canal para terminar a goroutine var chProcessEnd = make(chan bool, 1) // English: make a channel [optional] to print build output // Português: monta o canal [opcional] para imprimir a saída do build var chStatus = make(chan ContainerPullStatusSendToChannel, 1) // English: make a thread to monitoring and print channel data // Português: monta uma thread para imprimir os dados do canal go func(chStatus chan ContainerPullStatusSendToChannel, chProcessEnd chan bool) { for { select { case <-chProcessEnd: return case status := <-chStatus: // English: remove this comment to see all build status // Português: remova este comentário para vê todo o status da criação da imagem //fmt.Printf("image pull status: %+v\n", status) if status.Closed == true { // fmt.Println("image pull complete!") // English: Eliminate this goroutine after process end // Português: Elimina a goroutine após o fim do processo // return } } } }(chStatus, chProcessEnd) // English: searches for the folder containing the test server // Português: procura pela pasta contendo o servidor de teste var smallServerPath string smallServerPath, err = util.FileFindRecursivelyFullPath("small_test_server_port_3000") if err != nil { panic(err) } // English: create a new default client. Please, use: err, dockerSys = factoryDocker.NewClient() // Português: cria um novo cliente com configurações padrão. Por favor, usr: err, dockerSys = factoryDocker.NewClient() dockerSys = &DockerSystem{} dockerSys.ContextCreate() err = dockerSys.ClientCreate() if err != nil { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) } // English: build a new image from folder 'small_test_server_port_3000' // Português: monta uma imagem a partir da pasta 'small_test_server_port_3000' imageId, err = dockerSys.ImageBuildFromFolder( smallServerPath, "image_server_delete_before_test:latest", []string{}, types.ImageBuildOptions{}, chStatus, // [channel|nil] ) if err != nil { panic(err) } if imageId == "" { err = errors.New("image ID was not generated") panic(err) } // English: building a multi-step image leaves large and useless images, taking up space on the HD. // Português: construir uma imagem de múltiplas etapas deixa imagens grandes e sem serventia, ocupando espaço no HD. err = dockerSys.ImageGarbageCollector() if err != nil { panic(err) } // English: mount and start a container // Português: monta i inicializa o container containerId, err = dockerSys.ContainerCreate( // image name "image_server_delete_before_test:latest", // container name "container_delete_before_test", // restart policy KRestartPolicyUnlessStopped, // portMap nat.PortMap{ // container port number/protocol [tpc/udp] "3000/tcp": []nat.PortBinding{ // server original port { // server output port number HostPort: "9002", }, }, }, // mount volumes []mount.Mount{ { // bind - is the type for mounting host dir (real folder inside computer where // this code work) Type: KVolumeMountTypeVolumeString, // path inside host machine Source: "static_smallServer", // path inside image Target: "/static", }, }, // nil or container network configuration nil, ) if err != nil { panic(err) } if containerId == "" { err = errors.New("container id was not generated") panic(err) } // English: container start // Português: inicia o container err = dockerSys.ContainerStart(containerId) if err != nil { panic(err) } // English: ends a goroutine // Português: termina a goroutine chProcessEnd <- true var volume types.Volume volume, err = dockerSys.VolumeFindByName("static_smallServer") if err != nil { panic(err) } if volume.Name != "static_smallServer" { err = errors.New("volume name not found") panic(err) } if volume.Driver != "local" { err = errors.New("wrong volume drive") panic(err) } if volume.Scope != "local" { err = errors.New("wrong volume scope") panic(err) } err = dockerSys.ContainerStopAndRemove(containerId) if err != nil { panic(err) } err = dockerSys.VolumeRemove("static_smallServer") if err != nil { panic(err) } volume, err = dockerSys.VolumeFindByName("static_smallServer") if err != nil && err.Error() != "volume name not found" { panic(err) } // English: garbage collector and deletes networks and images whose name contains the term 'delete' // Português: coletor de lixo e apaga redes e imagens cujo o nome contém o temo 'delete' err = dockerSys.RemoveAllByNameContains("delete") if err != nil { panic(err) }
Output:
func (DockerSystem) VolumesUnreferencedRemove ¶
func (el DockerSystem) VolumesUnreferencedRemove() ( err error, )
Remove unreferenced volumes
type EndpointIPAMConfig ¶
type EndpointSettings ¶
type EndpointSettings struct { // Configurations IPAMConfig EndpointIPAMConfig Links []string Aliases []string // Operational data NetworkID string EndpointID string Gateway string IPAddress string IPPrefixLen int IPv6Gateway string GlobalIPv6Address string GlobalIPv6PrefixLen int MacAddress string DriverOpts map[string]string }
type ExecResult ¶
type HealthConfig ¶
type HealthConfig struct { // Test is the test to perform to check that the container is healthy. // An empty slice means to inherit the default. // The options are: // {} : inherit healthcheck // {"NONE"} : disable healthcheck // {"CMD", args...} : exec arguments directly // {"CMD-SHELL", command} : run command with system's default shell Test []string `json:",omitempty"` // Zero means to inherit. Durations are expressed as integer nanoseconds. Interval time.Duration `json:",omitempty"` // Interval is the time to wait between checks. Timeout time.Duration `json:",omitempty"` // Timeout is the time to wait before considering the check to have hung. StartPeriod time.Duration `json:",omitempty"` // The start period for the container to initialize before the retries starts to count down. // Retries is the number of consecutive failures needed to consider a container as unhealthy. // Zero means inherit. Retries int `json:",omitempty"` }
HealthConfig holds configuration settings for the HEALTHCHECK feature.
type IPv4Generator ¶
type IPv4Generator struct {
// contains filtered or unexported fields
}
func (*IPv4Generator) GetCurrentIP ¶
func (el *IPv4Generator) GetCurrentIP() (digitA, digitB, digitC, digitD byte)
func (*IPv4Generator) GetCurrentIPAsString ¶
func (el *IPv4Generator) GetCurrentIPAsString() (ip string)
func (*IPv4Generator) IncCurrentIP ¶
func (el *IPv4Generator) IncCurrentIP() ( err error, )
func (*IPv4Generator) Init ¶
func (el *IPv4Generator) Init( gatewayA, gatewayB, gatewayC, gatewayD, subnetA, subnetB, subnetC, subnetD, subnetCidr byte, ) ( err error, )
func (*IPv4Generator) InitWithString ¶
func (el *IPv4Generator) InitWithString( gateway string, subnet string, ) ( err error, )
func (IPv4Generator) String ¶
func (el IPv4Generator) String() (currentIP string)
type InspectVolumeMount ¶
type InspectVolumeMount struct { Type Type `json:",omitempty"` // Source specifies the name of the mount. Depending on mount type, this // may be a volume name or a host path, or even ignored. // Source is not supported for tmpfs (must be an empty value) Source string `json:",omitempty"` Target string `json:",omitempty"` ReadOnly bool `json:",omitempty"` Consistency Consistency `json:",omitempty"` }
type Mount ¶
type Mount struct { MountType VolumeMountType Source string Destination string }
MountType:
KVolumeMountTypeBind - TypeBind is the type for mounting host dir KVolumeMountTypeVolume - TypeVolume is the type for remote storage volumes KVolumeMountTypeTmpfs - TypeTmpfs is the type for mounting tmpfs KVolumeMountTypeNpipe - TypeNamedPipe is the type for mounting Windows named pipes
Source: relative file/dir path in computer Destination: full path inside container
type NetworkDrive ¶
type NetworkDrive int
const ( //KNetworkDriveBridge (English): The default network driver. // //If you don’t specify a driver, this is the type of network you are creating. Bridge networks are usually used //when your applications run in standalone containers that need to communicate. // //See bridge networks https://docs.docker.com/network/bridge/. KNetworkDriveBridge NetworkDrive = iota //KNetworkDriveHost (English): For standalone containers, remove network isolation between the container and the //Docker host, and use the host’s networking directly. // //Host is only available for swarm services on Docker 17.06 and higher. // //See use the host network. https://docs.docker.com/network/host/ KNetworkDriveHost //KNetworkDriveOverlay (English): Overlay networks connect multiple Docker daemons together and enable swarm services //to communicate with each other. // //You can also use overlay networks to facilitate communication between a swarm service and a standalone container, or //between two standalone containers on different Docker daemons. // //This strategy removes the need to do OS-level routing between these containers. // //See overlay networks. https://docs.docker.com/network/overlay/ KNetworkDriveOverlay //KNetworkDriveMacVLan (English): Macvlan networks allow you to assign a MAC address to a container, making it appear //as a physical device on your network. // //The Docker daemon routes traffic to containers by their MAC addresses. Using the macvlan driver is sometimes the //best choice when dealing with legacy applications that expect to be directly connected to the physical network, //rather than routed through the Docker host’s network stack. // //See Macvlan networks. https://docs.docker.com/network/macvlan/ KNetworkDriveMacVLan //KNetworkDriveNone (English): For this container, disable all networking. Usually used in conjunction with a custom //network driver. // //None is not available for swarm services. // //See disable container networking. https://docs.docker.com/network/none/ KNetworkDriveNone )
func (NetworkDrive) String ¶
func (el NetworkDrive) String() string
type NextNetworkAutoConfiguration ¶
type NextNetworkAutoConfiguration struct {
// contains filtered or unexported fields
}
func NewNetwork ¶
func NewNetwork(networkName string) ( networkId string, networkAutoConfiguration *NextNetworkAutoConfiguration, err error, )
NewNetwork (English): Create a network with gateway 10.0.0.1 and subnet 10.0.0.0/16
networkName: network name
NewNetwork (Português): Cria uma rede com gateway 10.0.0.1 e subnet 10.0.0.0/16
func NewNetworkWithHighAddress ¶
func NewNetworkWithHighAddress( networkName string, address byte, subnetMask byte, ) ( networkId string, networkAutoConfiguration *NextNetworkAutoConfiguration, err error, )
NewNetworkWithHighAddress (English): Create a network with gateway address.0.0.1 and subnet address.0.0.0/subnetMask
networkName: network name address: upper part of the address between 1 and 255 subnetMask: subnet mask. Examples: 2, 4, 8, 16, 32
NewNetworkWithHighAddress (Português): Cria uma rede com gateway address.0.0.1 e subnet address.0.0.0/subnetMask
networkName: nome da rede address: parte alta do endereço entre 1 e 255 subnetMask: máscara de rede. Exemplos: 2, 4, 8, 16, 32
func (*NextNetworkAutoConfiguration) GetCurrentIpAddress ¶
func (el *NextNetworkAutoConfiguration) GetCurrentIpAddress() (IP string, err error)
func (*NextNetworkAutoConfiguration) GetNext ¶
func (el *NextNetworkAutoConfiguration) GetNext() (IP string, networkConfig *network.NetworkingConfig, err error)
func (*NextNetworkAutoConfiguration) Init ¶
func (el *NextNetworkAutoConfiguration) Init(id, name, gateway, subnet string)
init a network for new container nInit("test", 10, 0, 0, 1) before use this function, use whaleAquarium.Docker.NetworkCreate("test")
type RestartPolicy ¶
type RestartPolicy int
const ( //Do not automatically restart the container. (the default) KRestartPolicyNo RestartPolicy = iota //Restart the container if it exits due to an error, which manifests as a non-zero exit //code. KRestartPolicyOnFailure //Always restart the container if it stops. If it is manually stopped, it is restarted //only when Docker daemon restarts or the container itself is manually restarted. (See the second bullet listed in restart policy details) KRestartPolicyAlways //Similar to always, except that when the container is stopped (manually or otherwise), //it is not restarted even after Docker daemon restarts. KRestartPolicyUnlessStopped )
func NewKRestartPolicyAlwaysRestart ¶
func NewKRestartPolicyAlwaysRestart() RestartPolicy
NewKRestartPolicyAlwaysRestart (English): Container restart policy, always restart
NewKRestartPolicyAlwaysRestart (Português): Política de reinício do container, sempre reinicia
func NewRestartPolicyOnFailureRestart ¶
func NewRestartPolicyOnFailureRestart() RestartPolicy
NewRestartPolicyOnFailureRestart (English): Container restart policy, on failure
NewRestartPolicyOnFailureRestart (Português): Política de reinício do container, quando falhar
func NewRestartPolicyRestartPolicyNoRestart ¶
func NewRestartPolicyRestartPolicyNoRestart() RestartPolicy
NewRestartPolicyRestartPolicyNoRestart (English): Container restart policy, no restart
NewRestartPolicyRestartPolicyNoRestart (Português): Política de reinício do container, não reiniciar
func NewRestartPolicyRestartPolicyUnlessStopped ¶
func NewRestartPolicyRestartPolicyUnlessStopped() RestartPolicy
NewRestartPolicyRestartPolicyUnlessStopped (English): Container restart policy, unless stopped
NewRestartPolicyRestartPolicyUnlessStopped (Português): Política de reinício do container, a menos que seja interrompido
func (RestartPolicy) String ¶
func (el RestartPolicy) String() string
type TerminalColor ¶
type TerminalColor struct {
// contains filtered or unexported fields
}
func (*TerminalColor) AnsiColor8ToHtmlColor ¶
func (el *TerminalColor) AnsiColor8ToHtmlColor(ansiValue []byte) (htmlTag []byte)
type VolumeMountType ¶
type VolumeMountType int
const ( // KVolumeMountTypeBind TypeBind is the type for mounting host dir (real folder inside computer where this code work) KVolumeMountTypeBind VolumeMountType = iota // KVolumeMountTypeVolume TypeVolume is the type for remote storage volumes KVolumeMountTypeVolume // KVolumeMountTypeTmpfs TypeTmpfs is the type for mounting tmpfs KVolumeMountTypeTmpfs // KVolumeMountTypeNpipe TypeNamedPipe is the type for mounting Windows named pipes KVolumeMountTypeNpipe )
func (VolumeMountType) String ¶
func (el VolumeMountType) String() string
Source Files
¶
- adjustImageName.go
- clientCreate.go
- consts.go
- containerCopyFrom.go
- containerCopyTo.go
- containerCreate.go
- containerCreateAndExposePortsAutomatically.go
- containerCreateAndStart.go
- containerCreateExposePortsAutomaticallyAndStart.go
- containerCreateWithConfig.go
- containerExecCommand.go
- containerFindIdByName.go
- containerFindIdByNameContains.go
- containerGetLasNameElement.go
- containerInspect.go
- containerInspectByName.go
- containerInspectByNameContains.go
- containerInspectJSon.go
- containerInspectJSonByName.go
- containerInspectParsed.go
- containerListAll.go
- containerListWithOptions.go
- containerLogs.go
- containerLogsWaitText.go
- containerLogsWaitTextWithTimeout.go
- containerNetworkInspect.go
- containerPause.go
- containerRemove.go
- containerRestart.go
- containerRestartWithTimeout.go
- containerStart.go
- containerStatsOneShot.go
- containerStatsOneShotByName.go
- containerStop.go
- containerStopAndRemove.go
- containerUnpause.go
- containerWaitStatusNextExit.go
- containerWaitStatusNotRunning.go
- containerWaitStatusRemoved.go
- contextCreate.go
- doc.go
- dockerInfo.go
- fileMakeAbsolutePath.go
- getConfig.go
- imageBuild.go
- imageBuildFolderContext.go
- imageBuildFromFolder.go
- imageBuildFromRemoteServer.go
- imageBuildPrepareFolderContextSupport.go
- imageFindIdByName.go
- imageFindIdByNameContains.go
- imageGarbageCollector.go
- imageInspect.go
- imageList.go
- imageListExposedNatPort.go
- imageListExposedPorts.go
- imageListExposedPortsByName.go
- imageListExposedVolumes.go
- imageListExposedVolumesByName.go
- imageMountNatPortListChangeExposed.go
- imageMountNatPortListChangeExposedWithIpAddress.go
- imagePull.go
- imagePullWriteChannel.go
- imageRemove.go
- imageRemoveByName.go
- imageVerifyVolume.go
- init.go
- networkConnect.go
- networkCreate.go
- networkDisconnect.go
- networkFindByName.go
- networkFindIdByNameContains.go
- networkFindNetworkTypeBridgePublic.go
- networkGetGenerator.go
- networkGetTheBiggestAddress.go
- networkInspect.go
- networkList.go
- networkListLocalCreated.go
- networkRemove.go
- networkRemoveByName.go
- networkVerifyName.go
- newClient.go
- newImagePullStatusChannel.go
- newNetwork.go
- newNetworkWithHighAddress.go
- newPullStatusMonitor.go
- newRestartPolicyAlways.go
- newRestartPolicyOnFailure.go
- newRestartPolicyRestartPolicyNoRestart.go
- newRestartPolicyRestartPolicyUnlessStopped.go
- newVolumeMount.go
- processReader.go
- removeAllByNameContains.go
- setHealthcheck.go
- setOnBuild.go
- terminalToHtml.go
- typeContainerNetworkData.go
- typeContainerNetworkDataList.go
- typeContainerPullProgress.go
- typeContainerPullProgressDetail.go
- typeContainerPullStatus.go
- typeContainerPullStatusSendToChannel.go
- typeContainerPullStatusSendToChannelCount.go
- typeDockerSystem.go
- typeHealthConfig.go
- typeIpV4Generator.go
- typeMount.go
- typeNameAndId.go
- typeNetworkDrive.go
- typeNextNetworkAutoConfiguration.go
- typeRestarPolice.go
- typeVolumeMountType.go
- volumeCreate.go
- volumeFindByName.go
- volumeInspect.go
- volumeList.go
- volumeRemove.go
- volumesUnreferencedRemove.go