Documentation ¶
Overview ¶
Package iotmakerdockerbuilder
English: Golang and Docker in a simple way.
This package facilitates the use of docker containers by golang code ¶
Português: Golang e Docker de forma simples.
Este pacote facilita o uso de containers docker por código golang
Index ¶
- Constants
- func GarbageCollector()
- type ContainerBuilder
- func (e *ContainerBuilder) AddFileOrFolderToLinkBetweenConputerHostAndContainer(computerHostPath, insideContainerPath string) (err error)
- func (e *ContainerBuilder) AddImageBuildOptionsBuildArgs(key string, value *string)
- func (e *ContainerBuilder) AddPortToChange(imagePort string, newPort string)
- func (e *ContainerBuilder) AddPortToDockerfileExpose(value string)
- func (e *ContainerBuilder) AddPortToExpose(value string)
- func (e *ContainerBuilder) ContainerBuildFromImage() (err error)
- func (e *ContainerBuilder) ContainerFindIdByName(name string) (id string, err error)
- func (e *ContainerBuilder) ContainerFindIdByNameContains(containsName string) (list []NameAndId, err error)
- func (e *ContainerBuilder) ContainerInspect() (inspect iotmakerdocker.ContainerInspect, err error)
- func (e *ContainerBuilder) ContainerPause() (err error)
- func (e *ContainerBuilder) ContainerRemove(removeVolumes bool) (err error)
- func (e *ContainerBuilder) ContainerStart() (err error)
- func (e *ContainerBuilder) ContainerStop() (err error)
- func (e *ContainerBuilder) FindCurrentIPV4Address() (IP string, err error)
- func (e *ContainerBuilder) FindTextInsideContainerLog(value string) (contains bool, err error)
- func (e *ContainerBuilder) GetChannelEvent() (channel *chan iotmakerdocker.ContainerPullStatusSendToChannel)
- func (e *ContainerBuilder) GetChannelOnContainerInspect() (channel *chan bool)
- func (e *ContainerBuilder) GetChannelOnContainerReady() (channel *chan bool)
- func (e *ContainerBuilder) GetContainerID() (ID string)
- func (e *ContainerBuilder) GetContainerLog() (log []byte, err error)
- func (e *ContainerBuilder) GetIPV4Address() (IP string)
- func (e *ContainerBuilder) GetIdByContainerName() (err error)
- func (e *ContainerBuilder) GetImageID() (ID string)
- func (e *ContainerBuilder) GetImageName() (name string)
- func (e *ContainerBuilder) GetLastInspect() (inspect iotmakerdocker.ContainerInspect)
- func (e *ContainerBuilder) GetLastLogs() (logs string)
- func (e *ContainerBuilder) GetNetworkGatewayIPV4() (IPV4 string)
- func (e *ContainerBuilder) GetNetworkGatewayIPV4ByNetworkName(networkName string) (IPV4 string, err error)
- func (e *ContainerBuilder) GetNetworkIPV4() (IPV4 string)
- func (e *ContainerBuilder) GetNetworkIPV4ByNetworkName(networkName string) (IPV4 string, err error)
- func (e *ContainerBuilder) GetNetworkInterface() (network isolatedNetwork.ContainerBuilderNetworkInterface)
- func (e *ContainerBuilder) ImageBuildFromFolder() (err error)
- func (e *ContainerBuilder) ImageBuildFromServer() (err error)
- func (e *ContainerBuilder) ImageFindIdByName(name string) (id string, err error)
- func (e *ContainerBuilder) ImageFindIdByNameContains(containsName string) (list []NameAndId, err error)
- func (e *ContainerBuilder) ImageListExposedPorts() (portList []nat.Port, err error)
- func (e *ContainerBuilder) ImageListExposedVolumes() (list []string, err error)
- func (e *ContainerBuilder) ImagePull() (err error)
- func (e *ContainerBuilder) ImageRemove() (err error)
- func (e *ContainerBuilder) ImageRemoveByName(name string) (err error)
- func (e *ContainerBuilder) Init() (err error)
- func (e *ContainerBuilder) MakeDefaultDockerfileForMe()
- func (e *ContainerBuilder) RemoveAllByNameContains(value string) (err error)
- func (e *ContainerBuilder) SetBuildFolderPath(value string)
- func (e *ContainerBuilder) SetCacheEnable(value bool)
- func (e *ContainerBuilder) SetContainerAttachStandardStreamsToTty(value bool)
- func (e *ContainerBuilder) SetContainerCommandToRunWhenStartingTheContainer(values []string)
- func (e *ContainerBuilder) SetContainerEntrypointToRunWhenStartingTheContainer(values []string)
- func (e *ContainerBuilder) SetContainerHealthcheck(value *HealthConfig)
- func (e *ContainerBuilder) SetContainerName(value string)
- func (e *ContainerBuilder) SetContainerRestartPolicyAlways()
- func (e *ContainerBuilder) SetContainerRestartPolicyNo()
- func (e *ContainerBuilder) SetContainerRestartPolicyOnFailure()
- func (e *ContainerBuilder) SetContainerRestartPolicyUnlessStopped()
- func (e *ContainerBuilder) SetContainerShellForShellFormOfRunCmdEntrypoint(values []string)
- func (e *ContainerBuilder) SetDockerfileBuilder(value DockerfileAuto)
- func (e *ContainerBuilder) SetEnvironmentVar(value []string)
- func (e *ContainerBuilder) SetGitCloneToBuild(url string)
- func (e *ContainerBuilder) SetGitCloneToBuildWithPrivateSSHKey(url, privateSSHKeyPath, password string)
- func (e *ContainerBuilder) SetGitCloneToBuildWithPrivateToken(url, privateToken string)
- func (e *ContainerBuilder) SetGitCloneToBuildWithUserPassworh(url, user, password string)
- func (e *ContainerBuilder) SetGitConfigFile(value string)
- func (e *ContainerBuilder) SetGitPathPrivateRepository(value string)
- func (e *ContainerBuilder) SetGitSshPassword(password string)
- func (e *ContainerBuilder) SetImageBuildOptionsCPUPeriod(value int64)
- func (e *ContainerBuilder) SetImageBuildOptionsCPUQuota(value int64)
- func (e *ContainerBuilder) SetImageBuildOptionsCPUSetCPUs(value string)
- func (e *ContainerBuilder) SetImageBuildOptionsCPUSetMems(value string)
- func (e *ContainerBuilder) SetImageBuildOptionsCPUShares(value int64)
- func (e *ContainerBuilder) SetImageBuildOptionsCacheFrom(values []string)
- func (e *ContainerBuilder) SetImageBuildOptionsExtraHosts(values []string)
- func (e *ContainerBuilder) SetImageBuildOptionsIsolationDefault()
- func (e *ContainerBuilder) SetImageBuildOptionsIsolationHyperV()
- func (e *ContainerBuilder) SetImageBuildOptionsIsolationProcess()
- func (e *ContainerBuilder) SetImageBuildOptionsMemory(value int64)
- func (e *ContainerBuilder) SetImageBuildOptionsMemorySwap(value int64)
- func (e *ContainerBuilder) SetImageBuildOptionsNoCache()
- func (e *ContainerBuilder) SetImageBuildOptionsPlatform(value string)
- func (e *ContainerBuilder) SetImageBuildOptionsSecurityOpt(value []string)
- func (e *ContainerBuilder) SetImageBuildOptionsSquash(value bool)
- func (e *ContainerBuilder) SetImageBuildOptionsTarget(value string)
- func (e *ContainerBuilder) SetImageName(value string)
- func (e *ContainerBuilder) SetInspectInterval(value time.Duration)
- func (e *ContainerBuilder) SetNetworkDocker(network isolatedNetwork.ContainerBuilderNetworkInterface)
- func (e *ContainerBuilder) SetOpenAllContainersPorts()
- func (e *ContainerBuilder) SetPrintBuildOnStrOut()
- func (e *ContainerBuilder) SetPrivateRepositoryAutoConfig() (err error)
- func (e *ContainerBuilder) SetSshIdRsaFile(value string)
- func (e *ContainerBuilder) SetSshKnownHostsFile(value string)
- func (e *ContainerBuilder) SetWaitString(value string)
- func (e *ContainerBuilder) SetWaitStringWithTimeout(value string, timeout time.Duration)
- func (e *ContainerBuilder) WaitForTextInContainerLog(value string) (dockerLogs string, err error)
- func (e *ContainerBuilder) WaitForTextInContainerLogWithTimeout(value string, timeout time.Duration) (dockerLogs string, err error)
- type DockerfileAuto
- type HealthConfig
- type NameAndId
- type NetworkChaos
- func (e *NetworkChaos) Init() (err error)
- func (e *NetworkChaos) SetContainerName(value string)
- func (e *NetworkChaos) SetFatherContainer(fatherContainer *ContainerBuilder)
- func (e *NetworkChaos) SetNetworkDocker(network isolatedNetwork.ContainerBuilderNetworkInterface)
- func (e *NetworkChaos) SetPorts(listenPort, outputPort int, invert bool)
Examples ¶
- ContainerBuilder.AddFileOrFolderToLinkBetweenConputerHostAndContainer
- ContainerBuilder.AddPortToChange
- ContainerBuilder.AddPortToExpose
- ContainerBuilder.ContainerBuildFromImage
- ContainerBuilder.FindCurrentIPV4Address
- ContainerBuilder.ImageBuildFromFolder
- ContainerBuilder.ImageListExposedPorts
- ContainerBuilder.ImageListExposedVolumes
- ContainerBuilder.ImagePull
- ContainerBuilder.SetEnvironmentVar
- ContainerBuilder.SetGitCloneToBuild
- ContainerBuilder.SetNetworkDocker
- NetworkChaos.Init
Constants ¶
const ( KKiloByte = 1024 KMegaByte = 1024 * 1024 KGigaByte = 1024 * 1024 * 1024 KTeraByte = 1024 * 1024 * 1024 * 1024 )
Variables ¶
This section is empty.
Functions ¶
func GarbageCollector ¶
func GarbageCollector()
GarbageCollector
English: A great use of this code is to build container during unit testing, and in this case, you can add the term delete to the name of all docker elements created during the test, so that they are deleted in a simple way. e.g..: network_to_delete_after_test
Português: Uma grande utilidade desse código é levantar container durante testes unitários, e nesse caso, você pode adicionar o termo delete ao nome de todos os elementos docker criado durante o teste, para que os mesmos sejam apagados de forma simples. ex.: network_to_delete_after_test
Types ¶
type ContainerBuilder ¶
type ContainerBuilder struct { IPV4Address string // contains filtered or unexported fields }
ContainerBuilder
English: Docker manager
Português: Gerenciador de containers e imagens docker
func (*ContainerBuilder) AddFileOrFolderToLinkBetweenConputerHostAndContainer ¶ added in v0.5.22
func (e *ContainerBuilder) AddFileOrFolderToLinkBetweenConputerHostAndContainer(computerHostPath, insideContainerPath string) (err error)
AddFileOrFolderToLinkBetweenConputerHostAndContainer
English: Links a file or folder between the computer host and the container.
computerHostPath: Path of the file or folder inside the host computer insideContainerPath: Path inside the container
Português: Vincula um arquivo ou pasta entre o computador e o container.
computerHostPath: Caminho do arquivo ou pasta no computador hospedeiro insideContainerPath: Caminho dentro do container
Example ¶
var err error GarbageCollector() var container = ContainerBuilder{} // new image name delete:latest container.SetImageName("delete:latest") // container name container_delete_server_after_test container.SetContainerName("container_delete_server_after_test") // git project to clone https://github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git container.SetGitCloneToBuild("https://github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git") // see SetGitCloneToBuildWithUserPassworh(), SetGitCloneToBuildWithPrivateSshKey() and // SetGitCloneToBuildWithPrivateToken() // set a waits for the text to appear in the standard container output to proceed [optional] container.SetWaitStringWithTimeout( "Stating server on port 3000", 10*time.Second, ) // change and open port 3000 to 3030 container.AddPortToChange( "3000", "3030", ) // replace container folder /static to host folder ./test/static err = container.AddFileOrFolderToLinkBetweenConputerHostAndContainer( "./test/static", "/static", ) if err != nil { log.Printf("container.AddFileOrFolderToLinkBetweenConputerHostAndContainer().error: %v", err.Error()) util.TraceToLog() panic(err) } // inicialize container object err = container.Init() if err != nil { util.TraceToLog() panic(err) } // builder new image from git project err = container.ImageBuildFromServer() if err != nil { util.TraceToLog() log.Printf("container.ImageBuildFromServer().error: %v", err.Error()) panic(err) } // container build from image delete:latest err = container.ContainerBuildFromImage() if err != nil { util.TraceToLog() log.Printf("container.ContainerBuildFromImage().error: %v", err.Error()) panic(err) } // container "container_delete_server_after_test" running and ready for use on this code point on port 3030 // read server inside a container on address http://localhost:3030/ var resp *http.Response resp, err = http.Get("http://localhost:3030/") if err != nil { util.TraceToLog() log.Printf("http.Get().error: %v", err.Error()) panic(err) } var body []byte body, err = ioutil.ReadAll(resp.Body) if err != nil { util.TraceToLog() log.Printf("http.Get().error: %v", err.Error()) panic(err) } // print output fmt.Printf("%s", body) GarbageCollector()
Output: <html><body><p>C is life! Golang is a evolution of C</p></body></html>
func (*ContainerBuilder) AddImageBuildOptionsBuildArgs ¶
func (e *ContainerBuilder) AddImageBuildOptionsBuildArgs(key string, value *string)
AddImageBuildOptionsBuildArgs
English: Set build-time variables (--build-arg)
key: argument key (e.g. Dockerfile: ARG key) value: argument value docker build --build-arg HTTP_PROXY=http://10.20.30.2:1234 see https://docs.docker.com/engine/reference/commandline/build/#set-build-time-variables---build-arg code: var key = "GIT_PRIVATE_REPO" var value = "github.com/yourgit" var container = ContainerBuilder{} container.AddImageBuildOptionsBuildArgs(key, &value) Dockerfile: FROM golang:1.16-alpine as builder ARG GIT_PRIVATE_REPO RUN go env -w GOPRIVATE=$GIT_PRIVATE_REPO
Português: Adiciona uma variável durante a construção (--build-arg)
key: chave do argumento (ex. Dockerfile: ARG key) value: valor do argumento docker build --build-arg HTTP_PROXY=http://10.20.30.2:1234 Veja https://docs.docker.com/engine/reference/commandline/build/#set-build-time-variables---build-arg code: var key = "GIT_PRIVATE_REPO" var value = "github.com/yourgit" var container = ContainerBuilder{} container.AddImageBuildOptionsBuildArgs(key, &value) Dockerfile: FROM golang:1.16-alpine as builder ARG GIT_PRIVATE_REPO RUN go env -w GOPRIVATE=$GIT_PRIVATE_REPO
func (*ContainerBuilder) AddPortToChange ¶
func (e *ContainerBuilder) AddPortToChange(imagePort string, newPort string)
AddPortToChange
English: Defines a new port to be exposed on the network and links with the port defined in the image
imagePort: port defined in the image, in the form of a numeric string newPort: new port value to be exposed on the network Nota: The ports exposed in the creation of the container can be defined by SetOpenAllContainersPorts(), AddPortToChange() e AddPortToExpose(); By default, all doors are closed; The ImageListExposedPorts() function returns all ports defined in the image to be exposed.
Português: Define uma nova porta a ser exposta na rede e vincula com a porta definida na imagem
imagePort: porta definida na imagem, na forma de string numérica newPort: novo valor da porta a se exposta na rede Nota: As portas expostas na criação do container pode ser definidas por SetOpenAllContainersPorts(), AddPortToChange() e AddPortToExpose(); Por padrão, todas as portas ficam fechadas; A função ImageListExposedPorts() retorna todas as portas definidas na imagem para serem expostas.
Example ¶
var err error GarbageCollector() var container = ContainerBuilder{} // new image name delete:latest container.SetImageName("delete:latest") // container name container_delete_server_after_test container.SetContainerName("container_delete_server_after_test") // git project to clone https://github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git container.SetGitCloneToBuild("https://github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git") // see SetGitCloneToBuildWithUserPassworh(), SetGitCloneToBuildWithPrivateSshKey() and // SetGitCloneToBuildWithPrivateToken() // set a waits for the text to appear in the standard container output to proceed [optional] container.SetWaitStringWithTimeout("Stating server on port 3000", 10*time.Second) // change and open port 3000 to 3030 container.AddPortToChange("3000", "3030") // replace container folder /static to host folder ./test/static err = container.AddFileOrFolderToLinkBetweenConputerHostAndContainer("./test/static", "/static") if err != nil { log.Printf("container.AddFileOrFolderToLinkBetweenConputerHostAndContainer().error: %v", err.Error()) util.TraceToLog() panic(err) } // inicialize container object err = container.Init() if err != nil { util.TraceToLog() panic(err) } // builder new image from git project err = container.ImageBuildFromServer() if err != nil { util.TraceToLog() log.Printf("container.ImageBuildFromServer().error: %v", err.Error()) panic(err) } // container build from image delete:latest err = container.ContainerBuildFromImage() if err != nil { util.TraceToLog() log.Printf("container.ContainerBuildFromImage().error: %v", err.Error()) panic(err) } // container "container_delete_server_after_test" running and ready for use on this code point on port 3030 // read server inside a container on address http://localhost:3030/ var resp *http.Response resp, err = http.Get("http://localhost:3030/") if err != nil { util.TraceToLog() log.Printf("http.Get().error: %v", err.Error()) panic(err) } var body []byte body, err = ioutil.ReadAll(resp.Body) if err != nil { util.TraceToLog() log.Printf("http.Get().error: %v", err.Error()) panic(err) } // print output fmt.Printf("%s", body) GarbageCollector()
Output: <html><body><p>C is life! Golang is a evolution of C</p></body></html>
func (*ContainerBuilder) AddPortToDockerfileExpose ¶ added in v0.5.40
func (e *ContainerBuilder) AddPortToDockerfileExpose(value string)
AddPortToDockerfileExpose (english): Add ports to dockerfile expose tag.
Input: value: port in string form (without a colon, ":")
AddPortToDockerfileExpose (português): Adiciona portas a tag expose do dockerfile.
Entrada: value: porta na forma de string (sem dois pontos, ":")
func (*ContainerBuilder) AddPortToExpose ¶ added in v0.5.18
func (e *ContainerBuilder) AddPortToExpose(value string)
AddPortToExpose
English: Defines the port to be exposed on the network
value: port in the form of a numeric string Note: The ports exposed in the creation of the container can be defined by SetOpenAllContainersPorts(), AddPortToChange() and AddPortToExpose(); By default, all doors are closed; The ImageListExposedPorts() function returns all ports defined in the image to be exposed.
Português: Define a porta a ser expostas na rede
value: porta na forma de string numérica Nota: As portas expostas na criação do container pode ser definidas por SetOpenAllContainersPorts(), AddPortToChange() e AddPortToExpose(); Por padrão, todas as portas ficam fechadas; A função ImageListExposedPorts() retorna todas as portas definidas na imagem para serem expostas.
Example ¶
var err error GarbageCollector() var container = ContainerBuilder{} // new image name delete:latest container.SetImageName("delete:latest") // container name container_delete_server_after_test container.SetContainerName("container_delete_server_after_test") // git project to clone https://github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git container.SetGitCloneToBuild("https://github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git") // see SetGitCloneToBuildWithUserPassworh(), SetGitCloneToBuildWithPrivateSshKey() and // SetGitCloneToBuildWithPrivateToken() // set a waits for the text to appear in the standard container output to proceed [optional] container.SetWaitStringWithTimeout("Stating server on port 3000", 20*time.Second) // open port 3000 [optional in this case: default code open all ports] container.AddPortToExpose("3000") // replace container folder /static to host folder ./test/static err = container.AddFileOrFolderToLinkBetweenConputerHostAndContainer("./test/static", "/static") if err != nil { log.Printf("container.AddFileOrFolderToLinkBetweenConputerHostAndContainer().error: %v", err.Error()) util.TraceToLog() panic(err) } // inicialize container object err = container.Init() if err != nil { util.TraceToLog() panic(err) } // builder new image from git project err = container.ImageBuildFromServer() if err != nil { util.TraceToLog() log.Printf("container.ImageBuildFromServer().error: %v", err.Error()) panic(err) } // container build from image delete:latest err = container.ContainerBuildFromImage() if err != nil { util.TraceToLog() log.Printf("container.ContainerBuildFromImage().error: %v", err.Error()) panic(err) } // container "container_delete_server_after_test" running and ready for use on this code point on port 3030 // read server inside a container on address http://localhost:3000/ var resp *http.Response resp, err = http.Get("http://localhost:3000/") if err != nil { util.TraceToLog() log.Printf("http.Get().error: %v", err.Error()) panic(err) } var body []byte body, err = ioutil.ReadAll(resp.Body) if err != nil { util.TraceToLog() log.Printf("http.Get().error: %v", err.Error()) panic(err) } // print output fmt.Printf("%s", body) GarbageCollector()
Output: <html><body><p>C is life! Golang is a evolution of C</p></body></html>
func (*ContainerBuilder) ContainerBuildFromImage ¶
func (e *ContainerBuilder) ContainerBuildFromImage() (err error)
ContainerBuildFromImage
English: transforms an image downloaded by ImagePull() or created by ImageBuildFromFolder() into a container
Português: transforma uma imagem baixada por ImagePull() ou criada por ImageBuildFromFolder() em container
Example ¶
var err error GarbageCollector() var container = ContainerBuilder{} // new image name delete:latest container.SetImageName("delete:latest") // container name container_delete_server_after_test container.SetContainerName("container_delete_server_after_test") // git project to clone https://github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git container.SetGitCloneToBuild("https://github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git") // see SetGitCloneToBuildWithUserPassworh(), SetGitCloneToBuildWithPrivateSshKey() and // SetGitCloneToBuildWithPrivateToken() // set a waits for the text to appear in the standard container output to proceed [optional] container.SetWaitStringWithTimeout("Stating server on port 3000", 10*time.Second) // change and open port 3000 to 3030 container.AddPortToChange("3000", "3030") // replace container folder /static to host folder ./test/static err = container.AddFileOrFolderToLinkBetweenConputerHostAndContainer("./test/static", "/static") if err != nil { log.Printf("container.AddFileOrFolderToLinkBetweenConputerHostAndContainer().error: %v", err.Error()) util.TraceToLog() panic(err) } // inicialize container object err = container.Init() if err != nil { util.TraceToLog() panic(err) } // builder new image from git project err = container.ImageBuildFromServer() if err != nil { util.TraceToLog() log.Printf("container.ImageBuildFromServer().error: %v", err.Error()) panic(err) } // container build from image delete:latest err = container.ContainerBuildFromImage() if err != nil { util.TraceToLog() log.Printf("container.ContainerBuildFromImage().error: %v", err.Error()) panic(err) } // container "container_delete_server_after_test" running and ready for use on this code point on port 3030 // read server inside a container on address http://localhost:3030/ var resp *http.Response resp, err = http.Get("http://localhost:3030/") if err != nil { util.TraceToLog() log.Printf("http.Get().error: %v", err.Error()) panic(err) } var body []byte body, err = ioutil.ReadAll(resp.Body) if err != nil { util.TraceToLog() log.Printf("http.Get().error: %v", err.Error()) panic(err) } // print output fmt.Printf("%s", body) GarbageCollector()
Output: <html><body><p>C is life! Golang is a evolution of C</p></body></html>
func (*ContainerBuilder) ContainerFindIdByName ¶ added in v0.5.19
func (e *ContainerBuilder) ContainerFindIdByName(name string) (id string, err error)
func (*ContainerBuilder) ContainerFindIdByNameContains ¶ added in v0.5.19
func (e *ContainerBuilder) ContainerFindIdByNameContains(containsName string) (list []NameAndId, err error)
func (*ContainerBuilder) ContainerInspect ¶
func (e *ContainerBuilder) ContainerInspect() (inspect iotmakerdocker.ContainerInspect, err error)
ContainerInspect
English: inspects the container
Português: inspeciona o container
func (*ContainerBuilder) ContainerPause ¶
func (e *ContainerBuilder) ContainerPause() (err error)
ContainerPause
English: pause the container
Português: pausa o container
func (*ContainerBuilder) ContainerRemove ¶
func (e *ContainerBuilder) ContainerRemove(removeVolumes bool) (err error)
ContainerRemove
English: stop and remove the container
removeVolumes: removes docker volumes linked to the container
Português: parar e remover o container
removeVolumes: remove os volumes docker vinculados ao container
func (*ContainerBuilder) ContainerStart ¶
func (e *ContainerBuilder) ContainerStart() (err error)
ContainerStart
English: initialize a newly created or paused container
Português: inicializar um container recém criado ou pausado
func (*ContainerBuilder) ContainerStop ¶
func (e *ContainerBuilder) ContainerStop() (err error)
ContainerStop
English: stop the container
Português: parar o container
func (*ContainerBuilder) FindCurrentIPV4Address ¶
func (e *ContainerBuilder) FindCurrentIPV4Address() (IP string, err error)
FindCurrentIPV4Address
English: Inspects the docker's network and returns the current IP of the container
Português: Inspeciona a rede do docker e devolve o IP atual do container
Example ¶
var err error GarbageCollector() var container = ContainerBuilder{} // set image name for docker pull container.SetImageName("nats:latest") // set a container name container.SetContainerName("container_delete_nats_after_test") // set a waits for the text to appear in the standard container output to proceed [optional] container.SetWaitStringWithTimeout("Listening for route connections on 0.0.0.0:6222", 10*time.Second) // inialize the container object err = container.Init() if err != nil { util.TraceToLog() panic(err) } // image nats:latest pull command [optional] err = container.ImagePull() if err != nil { util.TraceToLog() panic(err) } // container build and start from image nats:latest // waits for the text "Listening for route connections on 0.0.0.0:6222" to appear in the standard container output // to proceed err = container.ContainerBuildFromImage() if err != nil { util.TraceToLog() panic(err) } var IP string IP, err = container.FindCurrentIPV4Address() if err != nil { util.TraceToLog() panic(err) } if IP != container.GetIPV4Address() { err = errors.New("all ip address must be a samer IP") util.TraceToLog() panic(err) } // container "container_delete_nats_after_test" running and ready for use on this code point on var IP // all nats ports are open // you can use AddPortToExpose("4222"), to open only ports defineds inside code; // you can use AddPortToChange("4222", "1111") to open only ports defineds inside code and change port 4222 to port // 1111; // you can use SetDoNotOpenContainersPorts() to not open containers ports GarbageCollector() // use this function to remove image, ONLY before container stoped and deleted err = container.ImageRemoveByName("nats:latest") if err != nil { util.TraceToLog() panic(err) }
Output:
func (*ContainerBuilder) FindTextInsideContainerLog ¶
func (e *ContainerBuilder) FindTextInsideContainerLog(value string) (contains bool, err error)
FindTextInsideContainerLog
English: search for text in standard container output.
value: searched text
Português: procurar por um texto na saída padrão do container.
value: texto procurado
func (*ContainerBuilder) GetChannelEvent ¶
func (e *ContainerBuilder) GetChannelEvent() (channel *chan iotmakerdocker.ContainerPullStatusSendToChannel)
GetChannelEvent (english):
GetChannelEvent (português): Canal disparado durante o processo de image build ou container build e retorna informações como andamento do download da imagem, processo de extração da mesma entre outras informações
Waiting: Esperando o processo ser iniciado pelo docker Downloading: Estado do download da imagem, caso a mesma não exista na máquina host Count: Quantidade de blocos a serem baixados Current: Total de bytes baixados até o momento Total: Total de bytes a serem baixados Percent: Percentual atual do processo com uma casa decimal de precisão DownloadComplete: todo: fazer Extracting: Estado da extração da imagem baixada Count: Quantidade de blocos a serem extraídos Current: Total de bytes extraídos até o momento Total: Total de bytes a serem extraídos Percent: Percentual atual do processo com uma casa decimal de precisão PullComplete: todo: fazer ImageName: nome da imagem baixada ImageID: ID da imagem baixada. (Cuidado: este valor só é definido ao final do processo) ContainerID: ID do container criado. (Cuidado: este valor só é definido ao final do processo) Closed: todo: fazer Stream: saída padrão do container durante o processo de build SuccessfullyBuildContainer: sucesso ao fim do processo de build do container SuccessfullyBuildImage: sucesso ao fim do processo de build da imagem IdAuxiliaryImages: usado pelo coletor de lixo para apagar as imagens axiliares ao fim do processo de build
func (*ContainerBuilder) GetChannelOnContainerInspect ¶
func (e *ContainerBuilder) GetChannelOnContainerInspect() (channel *chan bool)
GetChannelOnContainerInspect
English: Channel triggered at each ticker cycle defined in SetInspectInterval()
Português: Canal disparado a cada ciclo do ticker definido em SetInspectInterval()
func (*ContainerBuilder) GetChannelOnContainerReady ¶
func (e *ContainerBuilder) GetChannelOnContainerReady() (channel *chan bool)
GetChannelOnContainerReady
English: Channel fired when the container is ready for use
Note: This channel expects the container to signal that it is ready, but it does not take into account whether the application contained in the container is ready. For this reason, it is recommended to use SetWaitString()
Português: Canal disparado quando o container está pronto para uso
Nota: Este canal espera o container sinalizar que está pronto, mas, ele não considera se a aplicação contida no container está pronta. Por isto, é recomendado o uso de SetWaitString()
func (*ContainerBuilder) GetContainerID ¶
func (e *ContainerBuilder) GetContainerID() (ID string)
GetContainerID
English: Returns the ID of the created container
Português: Retorna o ID do container criado
func (*ContainerBuilder) GetContainerLog ¶
func (e *ContainerBuilder) GetContainerLog() (log []byte, err error)
GetContainerLog
English: Returns the current standard output of the container.
Português: Retorna a saída padrão atual do container.
func (*ContainerBuilder) GetIPV4Address ¶
func (e *ContainerBuilder) GetIPV4Address() (IP string)
GetIPV4Address
English: Returns the last IP read from the container
Note: If the container is disconnected or connected to another network after creation, this information may change
Português: Retorna o último IP lido do container
Nota: Caso o container seja desconectado ou conectado a outra rede após a criação, esta informação pode mudar
func (*ContainerBuilder) GetIdByContainerName ¶
func (e *ContainerBuilder) GetIdByContainerName() (err error)
GetIdByContainerName
English: Returns the container ID defined in SetContainerName()
Português: Retorna o ID do container definido em SetContainerName()
func (*ContainerBuilder) GetImageID ¶
func (e *ContainerBuilder) GetImageID() (ID string)
GetImageID
English: Returns the image ID.
Português: Retorna o ID da imagem.
func (*ContainerBuilder) GetImageName ¶
func (e *ContainerBuilder) GetImageName() (name string)
GetImageName
English: Returns the name of the image.
Português: Retorna o nome da imagem.
func (*ContainerBuilder) GetLastInspect ¶
func (e *ContainerBuilder) GetLastInspect() (inspect iotmakerdocker.ContainerInspect)
GetLastInspect
English: Returns the container data based on the last ticker cycle defined in SetInspectInterval()
Note: the GetChannelOnContainerInspect() function returns the channel triggered by the ticker when the information is ready for use
Português: Retorna os dados do container baseado no último ciclo do ticker definido em SetInspectInterval()
Nota: a função GetChannelOnContainerInspect() retorna o canal disparado pelo ticker quando as informações estão prontas para uso
func (*ContainerBuilder) GetLastLogs ¶
func (e *ContainerBuilder) GetLastLogs() (logs string)
GetLastLogs
English: Returns the standard container output based on the last ticker cycle defined in SetInspectInterval()
Note: the GetChannelOnContainerInspect() function returns the channel triggered by the ticker when the information is ready for use
Português: Retorna a saída padrão do container baseado no último ciclo do ticker definido em SetInspectInterval()
Nota: a função GetChannelOnContainerInspect() retorna o canal disparado pelo ticker quando as informações estão prontas para uso
func (*ContainerBuilder) GetNetworkGatewayIPV4 ¶
func (e *ContainerBuilder) GetNetworkGatewayIPV4() (IPV4 string)
GetNetworkGatewayIPV4
English: Returns the gateway from the network to the IPV4 network
Português: Retorna o gateway da rede para rede IPV4
func (*ContainerBuilder) GetNetworkGatewayIPV4ByNetworkName ¶
func (e *ContainerBuilder) GetNetworkGatewayIPV4ByNetworkName(networkName string) (IPV4 string, err error)
GetNetworkGatewayIPV4ByNetworkName
English: If the container is connected to more than one network, this function returns the gateway of the chosen network.
Note: the default docker network is named "bridge"
Português: Caso o container esteja ligado em mais de uma rede, esta função devolve o gateway da rede escolhida.
Nota: a rede padrão do docker tem o nome "bridge"
func (*ContainerBuilder) GetNetworkIPV4 ¶
func (e *ContainerBuilder) GetNetworkIPV4() (IPV4 string)
GetNetworkIPV4
English: Return the IPV4 from the docker network
Português: Retorno o IPV4 da rede do docker
func (*ContainerBuilder) GetNetworkIPV4ByNetworkName ¶
func (e *ContainerBuilder) GetNetworkIPV4ByNetworkName(networkName string) (IPV4 string, err error)
GetNetworkIPV4ByNetworkName
English: If the container is connected to more than one network, this function returns the IPV4 of the chosen network.
Note: the default docker network is named "bridge"
Português: Caso o container esteja ligado em mais de uma rede, esta função devolve o IPV4 da rede escolhida.
Nota: a rede padrão do docker tem o nome "bridge"
func (*ContainerBuilder) GetNetworkInterface ¶
func (e *ContainerBuilder) GetNetworkInterface() (network isolatedNetwork.ContainerBuilderNetworkInterface)
GetNetworkInterface
English: Returns the object defined for the network control
Português: Retorna o objeto definido para o controle da rede
func (*ContainerBuilder) ImageBuildFromFolder ¶
func (e *ContainerBuilder) ImageBuildFromFolder() (err error)
ImageBuildFromFolder
English: transforms the contents of the folder defined in SetBuildFolderPath() into a docker image
Note: The folder must contain a dockerfile file, but since different uses can have different dockerfiles, the following order will be given when searching for the file: "Dockerfile-iotmaker", "Dockerfile", "dockerfile" in the root folder; If not found, a recursive search will be done for "Dockerfile" and "dockerfile"; If the project is in golang and the main.go file, containing the package main, is contained in the root folder, with the go.mod file, the MakeDefaultDockerfileForMe() function can be used to use a standard Dockerfile file
Português: transforma o conteúdo da pasta definida em SetBuildFolderPath() em uma imagem docker
Nota: A pasta deve conter um arquivo dockerfile, mas, como diferentes usos podem ter diferentes dockerfiles, será dada a seguinte ordem na busca pelo arquivo: "Dockerfile-iotmaker", "Dockerfile", "dockerfile" na pasta raiz. Se não houver encontrado, será feita uma busca recursiva por "Dockerfile" e "dockerfile" Caso o projeto seja em golang e o arquivo main.go, contendo o pacote main, esteja contido na pasta raiz, com o arquivo go.mod, pode ser usada a função MakeDefaultDockerfileForMe() para ser usado um arquivo Dockerfile padrão
Example ¶
package main import ( "fmt" iotmakerdocker "github.com/helmutkemper/iotmaker.docker/v1.0.1" "github.com/helmutkemper/util" "io/ioutil" "log" "net/http" "strings" "time" ) func ImageBuildViewer(ch *chan iotmakerdocker.ContainerPullStatusSendToChannel) { go func(ch *chan iotmakerdocker.ContainerPullStatusSendToChannel) { for { select { case event := <-*ch: var stream = event.Stream stream = strings.ReplaceAll(stream, "\n", "") stream = strings.ReplaceAll(stream, "\r", "") stream = strings.Trim(stream, " ") if stream == "" { continue } log.Printf("%v", stream) if event.Closed == true { return } } } }(ch) } func main() { var err error GarbageCollector() var container = ContainerBuilder{} // new image name delete:latest container.SetImageName("delete:latest") // set a folder path to make a new image container.SetBuildFolderPath("./test/server") container.MakeDefaultDockerfileForMe() // container name container_delete_server_after_test container.SetContainerName("container_delete_server_after_test") // set a waits for the text to appear in the standard container output to proceed [optional] container.SetWaitStringWithTimeout("starting server at port 3000", 10*time.Second) // change and open port 3000 to 3030 container.AddPortToExpose("3000") // replace container folder /static to host folder ./test/static err = container.AddFileOrFolderToLinkBetweenConputerHostAndContainer("./test/static", "/static") if err != nil { panic(err) } // show image build stram on std out ImageBuildViewer(container.GetChannelEvent()) // inicialize container object err = container.Init() if err != nil { panic(err) } // builder new image from folder err = container.ImageBuildFromFolder() if err != nil { panic(err) } // build a new container from image err = container.ContainerBuildFromImage() if err != nil { panic(err) } // Server is ready for use o port 3000 // read server inside a container on address http://localhost:3000/ var resp *http.Response resp, err = http.Get("http://localhost:3000/") if err != nil { util.TraceToLog() log.Printf("http.Get().error: %v", err.Error()) panic(err) } var body []byte body, err = ioutil.ReadAll(resp.Body) if err != nil { util.TraceToLog() log.Printf("http.Get().error: %v", err.Error()) panic(err) } // print output fmt.Printf("%s", body) GarbageCollector() }
Output: <html><body><p>C is life! Golang is a evolution of C</p></body></html>
func (*ContainerBuilder) ImageBuildFromServer ¶
func (e *ContainerBuilder) ImageBuildFromServer() (err error)
ImageBuildFromServer
English: Build a docker image from a project contained in a git repository.
Note: The repository can be defined by the methods SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(), SetGitCloneToBuildWithPrivateToken() and SetGitCloneToBuildWithUserPassworh(); SetPrivateRepositoryAutoConfig() copies the git credentials contained in ~/.ssh and the settings of ~/.gitconfig; The SetGitConfigFile(), SetSshIdRsaFile() and SetSshKnownHostsFile() functions can be used to set git security and configuration files manually.
Português: Monta uma imagem docker a partir de um projeto contido em um repositório git.
Nota: O repositório pode ser definido pelos métodos SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(), SetGitCloneToBuildWithPrivateToken() e SetGitCloneToBuildWithUserPassworh(); SetPrivateRepositoryAutoConfig() copia as credências do git contidas em ~/.ssh e as configurações de ~/.gitconfig; As funções SetGitConfigFile(), SetSshIdRsaFile() e SetSshKnownHostsFile() podem ser usadas para definir os arquivos de configurações se segurança do git manualmente.
func (*ContainerBuilder) ImageFindIdByName ¶ added in v0.5.19
func (e *ContainerBuilder) ImageFindIdByName(name string) (id string, err error)
func (*ContainerBuilder) ImageFindIdByNameContains ¶ added in v0.5.19
func (e *ContainerBuilder) ImageFindIdByNameContains(containsName string) (list []NameAndId, err error)
func (*ContainerBuilder) ImageListExposedPorts ¶
func (e *ContainerBuilder) ImageListExposedPorts() (portList []nat.Port, err error)
ImageListExposedPorts
English: Lists all the ports defined in the image to be exposed.
Note: The ports exposed in the creation of the container can be defined by SetOpenAllContainersPorts(), AddPortToChange() and AddPortToExpose(); By default, all doors are closed.
Português: Lista todas as portas definidas na imagem para serem expostas.
Nota: As portas expostas na criação do container podem ser definidas por SetOpenAllContainersPorts(), AddPortToChange() e AddPortToExpose(); Por padrão, todas as portas ficam fechadas.
Example ¶
var err error var portList []nat.Port // create a container var container = ContainerBuilder{} // set image name for docker pull container.SetImageName("nats:latest") err = container.Init() if err != nil { util.TraceToLog() panic(err) } err = container.ImagePull() if err != nil { util.TraceToLog() panic(err) } portList, err = container.ImageListExposedPorts() if err != nil { util.TraceToLog() panic(err) } var portsToPrint = make([]string, 0) for _, p := range portList { portsToPrint = append(portsToPrint, fmt.Sprintf("port: %v/%v\n", p.Port(), p.Proto())) } sort.Strings(portsToPrint) for _, print := range portsToPrint { fmt.Printf("%v", print) } err = container.ImageRemove() if err != nil { util.TraceToLog() panic(err) }
Output: port: 4222/tcp port: 6222/tcp port: 8222/tcp
func (*ContainerBuilder) ImageListExposedVolumes ¶
func (e *ContainerBuilder) ImageListExposedVolumes() (list []string, err error)
ImageListExposedVolumes
English: Lists all volumes defined in the image.
Note: Use the AddFileOrFolderToLinkBetweenConputerHostAndContainer() function to link folders and files between the host computer and the container
Português: Lista todos os volumes definidos na imagem.
Nota: Use a função AddFileOrFolderToLinkBetweenConputerHostAndContainer() para vincular pastas e arquivos entre o computador hospedeiro e o container
Example ¶
var err error var volumes []string GarbageCollector() var container = ContainerBuilder{} // new image name delete:latest container.SetImageName("delete:latest") // git project to clone https://github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git container.SetGitCloneToBuild("https://github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git") err = container.Init() if err != nil { util.TraceToLog() panic(err) } err = container.ImageBuildFromServer() if err != nil { util.TraceToLog() panic(err) } volumes, err = container.ImageListExposedVolumes() if err != nil { util.TraceToLog() panic(err) } fmt.Printf("%v", volumes[0]) GarbageCollector()
Output: /static
func (*ContainerBuilder) ImagePull ¶
func (e *ContainerBuilder) ImagePull() (err error)
ImagePull
English: downloads the image to be mounted. (equivalent to the docker pull image command)
Português: baixa a imagem a ser montada. (equivale ao comando docker pull image)
Example ¶
var err error GarbageCollector() // create a network [optional] var netDocker = dockerNetwork.ContainerBuilderNetwork{} err = netDocker.Init() if err != nil { util.TraceToLog() panic(err) } // create a network named cache_delete_after_test, subnet 10.0.0.0/16 e gatway 10.0.0.1 err = netDocker.NetworkCreate("cache_delete_after_test", "10.0.0.0/16", "10.0.0.1") if err != nil { util.TraceToLog() panic(err) } // create a container var container = ContainerBuilder{} // link container and network [optional] (next ip address is 10.0.0.2) container.SetNetworkDocker(&netDocker) // set image name for docker pull container.SetImageName("nats:latest") // set a container name container.SetContainerName("container_delete_nats_after_test") // set a waits for the text to appear in the standard container output to proceed [optional] container.SetWaitStringWithTimeout("Listening for route connections on 0.0.0.0:6222", 10*time.Second) // inialize the container object err = container.Init() if err != nil { util.TraceToLog() panic(err) } // image nats:latest pull command [optional] err = container.ImagePull() if err != nil { util.TraceToLog() panic(err) } // container build and start from image nats:latest // waits for the text "Listening for route connections on 0.0.0.0:6222" to appear in the standard container output // to proceed err = container.ContainerBuildFromImage() if err != nil { util.TraceToLog() panic(err) } // container "container_delete_nats_after_test" running and ready for use on this code point on IP 10.0.0.2 // all nats ports are open // you can use AddPortToExpose("4222"), to open only ports defineds inside code; // you can use AddPortToChange("4222", "1111") to open only ports defineds inside code and change port 4222 to port // 1111; // you can use SetDoNotOpenContainersPorts() to not open containers ports GarbageCollector() // use this function to remove image, ONLY before container stoped and deleted err = container.ImageRemoveByName("nats:latest") if err != nil { util.TraceToLog() panic(err) }
Output:
func (*ContainerBuilder) ImageRemove ¶
func (e *ContainerBuilder) ImageRemove() (err error)
ImageRemove
English: remove the image if there are no containers using the image (remove all containers before use, including stopped containers)
Português: remove a imagem se não houver containers usando a imagem (remova todos os containers antes do uso, inclusive os containers parados)
func (*ContainerBuilder) ImageRemoveByName ¶
func (e *ContainerBuilder) ImageRemoveByName(name string) (err error)
ImageRemoveByName
English: remove the image if there are no containers using the image (remove all containers before use, including stopped containers)
name: full image name
Português: remove a imagem se não houver containers usando a imagem (remova todos os containers antes do uso, inclusive os containers parados)
name: nome completo da imagem
func (*ContainerBuilder) Init ¶
func (e *ContainerBuilder) Init() (err error)
Init
English: Initializes the object and should be called only after all settings have been configured
Português: Inicializa o objeto e deve ser chamado apenas depois de toas as configurações serem definidas
func (*ContainerBuilder) MakeDefaultDockerfileForMe ¶
func (e *ContainerBuilder) MakeDefaultDockerfileForMe()
MakeDefaultDockerfileForMe
English: Automatically mount the Dockerfile-iotmaker inside the target folder.
If there are ports exposed in the configurations, they will be defined automatically and the same goes for volumes, where files shared between the host and the container will expose the folder containing the file inside the container as volume.
Caution: the Dockerfile-iotmaker may be overwritten. Rules: For Golang projects, the go.mod file is mandatory; The main.go file containing the main package must be at the root folder. Note: If you need a dockerfile made for another programming language, see the DockerfileAuto interface and the SetDockerfileBuilder() function
Português: Monta o arquivo Dockerfile-iotmaker dentro da pasta alvo de forma automática.
Caso haja portas expostas nas configurações, as mesmas serão definidas automaticamente e o mesmo vale para volumes, onde arquivos compartilhados entre o host e o container exporá a pasta contendo o arquivo dentro do container como um volume.
Cuidado: o arquivo Dockerfile-iotmaker pode ser sobrescrito. Regras: Para projetos Golang, o arquivo go.mod é obrigatório; O arquivo main.go contendo o package main deve está na raiz do diretório. Nota: Caso necessite de um dockerfile feito para outra linguagem de programação, veja a interface DockerfileAuto e a função SetDockerfileBuilder()
func (*ContainerBuilder) RemoveAllByNameContains ¶
func (e *ContainerBuilder) RemoveAllByNameContains(value string) (err error)
RemoveAllByNameContains
English: searches for networks, volumes, containers and images that contain the term defined in "value" in the name, and tries to remove them from docker
Português: procura por redes, volumes, container e imagens que contenham o termo definido em "value" no nome, e tenta remover os mesmos do docker
func (*ContainerBuilder) SetBuildFolderPath ¶
func (e *ContainerBuilder) SetBuildFolderPath(value string)
SetBuildFolderPath
English: Defines the path of the folder to be transformed into an image
value: path of the folder to be transformed into an image Note: The folder must contain a dockerfile file, but since different uses can have different dockerfiles, the following order will be given when searching for the file: "Dockerfile-iotmaker", "Dockerfile", "dockerfile" in the root folder; If not found, a recursive search will be done for "Dockerfile" and "dockerfile"; If the project is in golang and the main.go file, containing the package main, is contained in the root folder, with the go.mod file, the MakeDefaultDockerfileForMe() function can be used to use a standard Dockerfile file
Português: Define o caminho da pasta a ser transformada em imagem
value: caminho da pasta a ser transformada em imagem Nota: A pasta deve conter um arquivo dockerfile, mas, como diferentes usos podem ter diferentes dockerfiles, será dada a seguinte ordem na busca pelo arquivo: "Dockerfile-iotmaker", "Dockerfile", "dockerfile" na pasta raiz. Se não houver encontrado, será feita uma busca recursiva por "Dockerfile" e "dockerfile" Caso o projeto seja em golang e o arquivo main.go, contendo o pacote main, esteja contido na pasta raiz, com o arquivo go.mod, pode ser usada a função MakeDefaultDockerfileForMe() para ser usado um arquivo Dockerfile padrão
func (*ContainerBuilder) SetCacheEnable ¶ added in v0.5.40
func (e *ContainerBuilder) SetCacheEnable(value bool)
SetCacheEnable (english): When true, looks for an image named `chache:latest` as a basis for creating new images when the MakeDefaultDockerfileForMe function is used.
This function is extremely useful when developing new applications, reducing the time to create images with each new test.
Entrada: value: true to enable the use of image named cache:latest as the basis for new images if it exists
Example:
Folder: cache File: Dockerfile-iotmaker Need: Image with nats.io drive installed Content: FROM golang:1.16-alpine as builder RUN mkdir -p /root/.ssh/ && \ apk update && \ apk add --no-cache build-base && \ apk add --no-cache alpine-sdk && \ rm -rf /var/cache/apk/* ARG CGO_ENABLED=0 RUN go get -u github.com/nats-io/nats.go
Code Golang:
var imageCacheName = "cache:latest" var imageId string var container = &dockerBuilder.ContainerBuilder{} imageId, err = container.ImageFindIdByName(imageCacheName) if err != nil && err.Error() != "image name not found" { return } if imageId != "" { return } container.SetImageName(imageCacheName) container.SetPrintBuildOnStrOut() container.SetContainerName(imageCacheName) container.SetBuildFolderPath("./cache") err = container.Init() if err != nil { return } err = container.ImageBuildFromFolder() if err != nil { return }
SetCacheEnable (português): Quando true, procura por uma imagem de nome `chache:latest` como base para a criação de novas imagens quando a função MakeDefaultDockerfileForMe é usada.
Esta função é extremamente útil no desenvolvimento de novas aplicações, reduzindo o tempo de criação de imagens a cada novo teste.
Entrada: value: true para habilitar o uso da imagem de nome cache:latest como base para novas imagens, caso a mesma exista
Exemplo:
Pasta: cache Arquivo: Dockerfile-iotmaker Necessidade: Imagem com o drive do nats.io instalada Conteúdo: FROM golang:1.16-alpine as builder RUN mkdir -p /root/.ssh/ && \ apk update && \ apk add --no-cache build-base && \ apk add --no-cache alpine-sdk && \ rm -rf /var/cache/apk/* ARG CGO_ENABLED=0 RUN go get -u github.com/nats-io/nats.go
Código Golang:
var imageCacheName = "cache:latest" var imageId string var container = &dockerBuilder.ContainerBuilder{} imageId, err = container.ImageFindIdByName(imageCacheName) if err != nil && err.Error() != "image name not found" { return } if imageId != "" { return } container.SetImageName(imageCacheName) container.SetPrintBuildOnStrOut() container.SetContainerName(imageCacheName) container.SetBuildFolderPath("./cache") err = container.Init() if err != nil { return } err = container.ImageBuildFromFolder() if err != nil { return }
func (*ContainerBuilder) SetContainerAttachStandardStreamsToTty ¶
func (e *ContainerBuilder) SetContainerAttachStandardStreamsToTty(value bool)
SetContainerAttachStandardStreamsToTty
English: attach standard streams to tty
Português: anexa a saída padrão do tty
func (*ContainerBuilder) SetContainerCommandToRunWhenStartingTheContainer ¶
func (e *ContainerBuilder) SetContainerCommandToRunWhenStartingTheContainer(values []string)
SetContainerCommandToRunWhenStartingTheContainer
English: command to run when stating the container (style Dockerfile CMD)
Português: comando a ser executado quando o container inicia (estilo Dockerfile CMD)
func (*ContainerBuilder) SetContainerEntrypointToRunWhenStartingTheContainer ¶
func (e *ContainerBuilder) SetContainerEntrypointToRunWhenStartingTheContainer(values []string)
SetContainerEntrypointToRunWhenStartingTheContainer
English: entrypoint to run when stating the container
Português: entrypoint a ser executado quando o container inicia
func (*ContainerBuilder) SetContainerHealthcheck ¶
func (e *ContainerBuilder) SetContainerHealthcheck(value *HealthConfig)
SetContainerHealthcheck
English: holds configuration settings for the HEALTHCHECK feature.
Test: 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 Interval: Interval is the time to wait between checks (Zero means inherit). Timeout: Timeout is the time to wait before considering the check to have hung (Zero means inherit). StartPeriod: The start period for the container to initialize before the retries starts to count down (Zero means inherit). Retries: Retries is the number of consecutive failures needed to consider a container as unhealthy (Zero means inherit).
Português: define definições de configuração para o recurso HEALTHCHECK.
Test: Test é o teste a ser executado para testar a saúde do container se não for definido, herda o teste padrão As opções são: {}: herda o teste padrão {"NONE"}: desabilita o healthcheck {"CMD", args...}: executa os argumentos diretamente {"CMD-SHELL", command} : executa o comando com shell padrão do sistema Interval: intervalo entre testes (zero herda o valor padrão). Timeout: intervalo de espera antes de considerar o teste com problemas (zero herda o valor padrão). StartPeriod: tempo de espera pela incialização do container antes dos testes começarem (zero herda o valor padrão). Retries: número de testes consecutivos antes de considerar o teste com problemas (zero herda o valor padrão).
func (*ContainerBuilder) SetContainerName ¶
func (e *ContainerBuilder) SetContainerName(value string)
SetContainerName
English: Defines the name of the container
value: container name
Português: Define o nome do container
value: nome do container
func (*ContainerBuilder) SetContainerRestartPolicyAlways ¶
func (e *ContainerBuilder) SetContainerRestartPolicyAlways()
SetContainerRestartPolicyAlways
English: 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.
Português: Define a política de reinício do container como sempre reinicia o container quando ele para, mesmo quando ele é parado manualmente.
func (*ContainerBuilder) SetContainerRestartPolicyNo ¶
func (e *ContainerBuilder) SetContainerRestartPolicyNo()
SetContainerRestartPolicyNo
English: Do not automatically restart the container. (the default)
Português: Define a política de reinício do container como não reiniciar o container (padrão).
func (*ContainerBuilder) SetContainerRestartPolicyOnFailure ¶
func (e *ContainerBuilder) SetContainerRestartPolicyOnFailure()
SetContainerRestartPolicyOnFailure
English: Restart the container if it exits due to an error, which manifests as a non-zero exit code
Português: Define a política de reinício do container como reinicia o container se houver um erro (com o manifesto informando um código de erro diferente de zero).
func (*ContainerBuilder) SetContainerRestartPolicyUnlessStopped ¶
func (e *ContainerBuilder) SetContainerRestartPolicyUnlessStopped()
SetContainerRestartPolicyUnlessStopped
English: Similar to always, except that when the container is stopped (manually or otherwise), it is not restarted even after Docker daemon restarts.
Português: Define a política de reinício do container como sempre reinicia o container, caso ele não tenha sido parado manualmente.
func (*ContainerBuilder) SetContainerShellForShellFormOfRunCmdEntrypoint ¶
func (e *ContainerBuilder) SetContainerShellForShellFormOfRunCmdEntrypoint(values []string)
SetContainerShellForShellFormOfRunCmdEntrypoint
English: shell for shell-form of run cmd entrypoint
Português: define o terminal (shell) para executar o entrypoint
func (*ContainerBuilder) SetDockerfileBuilder ¶ added in v0.5.11
func (e *ContainerBuilder) SetDockerfileBuilder(value DockerfileAuto)
SetDockerfileBuilder
English: Defines a new object containing the builder of the dockerfile.
Note: see the DockerfileAuto interface for further instructions.
Português: Define um novo objeto contendo o construtor do arquivo dockerfile.
Nota: veja a interface DockerfileAuto para mais instruções.
func (*ContainerBuilder) SetEnvironmentVar ¶
func (e *ContainerBuilder) SetEnvironmentVar(value []string)
SetEnvironmentVar
English: Defines environment variables
value: slice of string containing one environment variable per key
Português: Define as variáveis de ambiente
value: slice de string contendo um variável de ambiente por chave
Example ¶
var err error GarbageCollector() var netDocker = dockerNetwork.ContainerBuilderNetwork{} err = netDocker.Init() if err != nil { panic(err) } // create a network named cache_delete_after_test, subnet 10.0.0.0/16 e gatway 10.0.0.1 err = netDocker.NetworkCreate("cache_delete_after_test", "10.0.0.0/16", "10.0.0.1") if err != nil { panic(err) } // At this point in the code, the network has been created and is ready for use var mongoDocker = &ContainerBuilder{} // set a docker network //mongoDocker.SetNetworkDocker(&netDocker) // set an image name mongoDocker.SetImageName("mongo:latest") // set a container name mongoDocker.SetContainerName("container_delete_mongo_after_test") // set a port to expose mongoDocker.AddPortToExpose("27017") // se a environment var list mongoDocker.SetEnvironmentVar( []string{ "--host 0.0.0.0", }, ) // set a MongoDB data dir to ./test/data //err = mongoDocker.AddFileOrFolderToLinkBetweenConputerHostAndContainer("./test/data", "/data") if err != nil { panic(err) } // set a text indicating for container ready for use mongoDocker.SetWaitStringWithTimeout(`"msg":"Waiting for connections","attr":{"port":27017`, 20*time.Second) // inicialize the object before sets err = mongoDocker.Init() if err != nil { panic(err) } // build a container err = mongoDocker.ContainerBuildFromImage() if err != nil { panic(err) } // Output: // // At this point, the MongoDB is ready for use on port 27017 // Stop and delete the container // GarbageCollector()
Output:
func (*ContainerBuilder) SetGitCloneToBuild ¶
func (e *ContainerBuilder) SetGitCloneToBuild(url string)
SetGitCloneToBuild
English: Defines the path of a repository to be used as the base of the image to be mounted.
url: Address of the repository containing the project Note: If the repository is private and the host computer has access to the git server, use SetPrivateRepositoryAutoConfig() to copy the git credentials contained in ~/.ssh and the settings of ~/.gitconfig automatically; To be able to access private repositories from inside the container, build the image in two or more steps and in the first step, copy the id_rsa and known_hosts files to the /root/.ssh folder, and the ~/.gitconfig file to the /root folder; The MakeDefaultDockerfileForMe() function make a standard dockerfile with the procedures above; If the ~/.ssh/id_rsa key is password protected, use the SetGitSshPassword() function to set the password; If you want to define the files manually, use SetGitConfigFile(), SetSshKnownHostsFile() and SetSshIdRsaFile() to define the files manually; This function must be used with the ImageBuildFromServer() and SetImageName() function to download and generate an image from the contents of a git repository; The repository must contain a Dockerfile file and it will be searched for in the following order: './Dockerfile-iotmaker', './Dockerfile', './dockerfile', 'Dockerfile.*', 'dockerfile.*', '.*Dockerfile.*' and '.*dockerfile.*'; The repository can be defined by the methods SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(), SetGitCloneToBuildWithPrivateToken() and SetGitCloneToBuildWithUserPassworh().
Português: Define o caminho de um repositório para ser usado como base da imagem a ser montada.
url: Endereço do repositório contendo o projeto Nota: Caso o repositório seja privado e o computador hospedeiro tenha acesso ao servidor git, use SetPrivateRepositoryAutoConfig() para copiar as credências do git contidas em ~/.ssh e as configurações de ~/.gitconfig de forma automática; Para conseguir acessar repositórios privados de dentro do container, construa a imagem em duas ou mais etapas e na primeira etapa, copie os arquivos id_rsa e known_hosts para a pasta /root/.ssh e o arquivo .gitconfig para a pasta /root/; A função MakeDefaultDockerfileForMe() monta um dockerfile padrão com os procedimentos acima; Caso a chave ~/.ssh/id_rsa seja protegida com senha, use a função SetGitSshPassword() para definir a senha da mesma; Caso queira definir os arquivos de forma manual, use SetGitConfigFile(), SetSshKnownHostsFile() e SetSshIdRsaFile() para definir os arquivos de forma manual; Esta função deve ser usada com a função ImageBuildFromServer() e SetImageName() para baixar e gerar uma imagem a partir do conteúdo de um repositório git; O repositório deve contar um arquivo Dockerfile e ele será procurado na seguinte ordem: './Dockerfile-iotmaker', './Dockerfile', './dockerfile', 'Dockerfile.*', 'dockerfile.*', '.*Dockerfile.*' e '.*dockerfile.*'; O repositório pode ser definido pelos métodos SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(), SetGitCloneToBuildWithPrivateToken() e SetGitCloneToBuildWithUserPassworh().
Example ¶
var err error GarbageCollector() var container = ContainerBuilder{} // new image name delete:latest container.SetImageName("delete:latest") // container name container_delete_server_after_test container.SetContainerName("container_delete_server_after_test") // git project to clone https://github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git container.SetGitCloneToBuild("https://github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git") // set a waits for the text to appear in the standard container output to proceed [optional] container.SetWaitStringWithTimeout("Stating server on port 3000", 10*time.Second) // change and open port 3000 to 3030 container.AddPortToChange("3000", "3030") // replace container folder /static to host folder ./test/static err = container.AddFileOrFolderToLinkBetweenConputerHostAndContainer("./test/static", "/static") if err != nil { panic(err) } // inicialize container object err = container.Init() if err != nil { panic(err) } // builder new image from git project err = container.ImageBuildFromServer() if err != nil { panic(err) } // build a new container from image err = container.ContainerBuildFromImage() if err != nil { panic(err) } // At this point, the container is ready for use on port 3030 // Stop and delete the container GarbageCollector()
Output:
func (*ContainerBuilder) SetGitCloneToBuildWithPrivateSSHKey ¶
func (e *ContainerBuilder) SetGitCloneToBuildWithPrivateSSHKey(url, privateSSHKeyPath, password string)
SetGitCloneToBuildWithPrivateSSHKey
English: Defines the path of a repository to be used as the base of the image to be mounted.
url: Address of the repository containing the project privateSSHKeyPath: this is the path of the private ssh key compatible with the public key registered in git password: password used when the ssh key was generated or empty string Note: If the repository is private and the host computer has access to the git server, use SetPrivateRepositoryAutoConfig() to copy the git credentials contained in ~/.ssh and the settings of ~/.gitconfig automatically; To be able to access private repositories from inside the container, build the image in two or more steps and in the first step, copy the id_rsa and known_hosts files to the /root/.ssh folder, and the ~/.gitconfig file to the /root folder; The MakeDefaultDockerfileForMe() function make a standard dockerfile with the procedures above; If the ~/.ssh/id_rsa key is password protected, use the SetGitSshPassword() function to set the password; If you want to define the files manually, use SetGitConfigFile(), SetSshKnownHostsFile() and SetSshIdRsaFile() to define the files manually; This function must be used with the ImageBuildFromServer() and SetImageName() function to download and generate an image from the contents of a git repository; The repository must contain a Dockerfile file and it will be searched for in the following order: './Dockerfile-iotmaker', './Dockerfile', './dockerfile', 'Dockerfile.*', 'dockerfile.*', '.*Dockerfile.*' and '.*dockerfile.*'; The repository can be defined by the methods SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(), SetGitCloneToBuildWithPrivateToken() and SetGitCloneToBuildWithUserPassworh(). code: var err error var usr *user.User var privateSSHKeyPath string var userGitConfigPath string var file []byte usr, err = user.Current() if err != nil { panic(err) } privateSSHKeyPath = filepath.Join(usr.HomeDir, ".shh", "id_rsa") userGitConfigPath = filepath.Join(usr.HomeDir, ".gitconfig") file, err = ioutil.ReadFile(userGitConfigPath) var container = ContainerBuilder{} container.SetGitCloneToBuildWithPrivateSSHKey(url, privateSSHKeyPath, password) container.SetGitConfigFile(string(file))
Português: Define o caminho de um repositório para ser usado como base da imagem a ser montada.
url: Endereço do repositório contendo o projeto privateSSHKeyPath: este é o caminho da chave ssh privada compatível com a chave pública cadastrada no git password: senha usada no momento que a chave ssh foi gerada ou string em branco Nota: Caso o repositório seja privado e o computador hospedeiro tenha acesso ao servidor git, use SetPrivateRepositoryAutoConfig() para copiar as credências do git contidas em ~/.ssh e as configurações de ~/.gitconfig de forma automática; Para conseguir acessar repositórios privados de dentro do container, construa a imagem em duas ou mais etapas e na primeira etapa, copie os arquivos id_rsa e known_hosts para a pasta /root/.ssh e o arquivo .gitconfig para a pasta /root/; A função MakeDefaultDockerfileForMe() monta um dockerfile padrão com os procedimentos acima; Caso a chave ~/.ssh/id_rsa seja protegida com senha, use a função SetGitSshPassword() para definir a senha da mesma; Caso queira definir os arquivos de forma manual, use SetGitConfigFile(), SetSshKnownHostsFile() e SetSshIdRsaFile() para definir os arquivos de forma manual; Esta função deve ser usada com a função ImageBuildFromServer() e SetImageName() para baixar e gerar uma imagem a partir do conteúdo de um repositório git; O repositório deve contar um arquivo Dockerfile e ele será procurado na seguinte ordem: './Dockerfile-iotmaker', './Dockerfile', './dockerfile', 'Dockerfile.*', 'dockerfile.*', '.*Dockerfile.*' e '.*dockerfile.*'; O repositório pode ser definido pelos métodos SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(), SetGitCloneToBuildWithPrivateToken() e SetGitCloneToBuildWithUserPassworh(). code: var err error var usr *user.User var privateSSHKeyPath string var userGitConfigPath string var file []byte usr, err = user.Current() if err != nil { panic(err) } privateSSHKeyPath = filepath.Join(usr.HomeDir, ".shh", "id_rsa") userGitConfigPath = filepath.Join(usr.HomeDir, ".gitconfig") file, err = ioutil.ReadFile(userGitConfigPath) var container = ContainerBuilder{} container.SetGitCloneToBuildWithPrivateSSHKey(url, privateSSHKeyPath, password) container.SetGitConfigFile(string(file))
func (*ContainerBuilder) SetGitCloneToBuildWithPrivateToken ¶
func (e *ContainerBuilder) SetGitCloneToBuildWithPrivateToken(url, privateToken string)
SetGitCloneToBuildWithPrivateToken
English: Defines the path of a repository to be used as the base of the image to be mounted.
url: Address of the repository containing the project privateToken: token defined on your git tool portal Note: If the repository is private and the host computer has access to the git server, use SetPrivateRepositoryAutoConfig() to copy the git credentials contained in ~/.ssh and the settings of ~/.gitconfig automatically; To be able to access private repositories from inside the container, build the image in two or more steps and in the first step, copy the id_rsa and known_hosts files to the /root/.ssh folder, and the ~/.gitconfig file to the /root folder; The MakeDefaultDockerfileForMe() function make a standard dockerfile with the procedures above; If the ~/.ssh/id_rsa key is password protected, use the SetGitSshPassword() function to set the password; If you want to define the files manually, use SetGitConfigFile(), SetSshKnownHostsFile() and SetSshIdRsaFile() to define the files manually; This function must be used with the ImageBuildFromServer() and SetImageName() function to download and generate an image from the contents of a git repository; The repository must contain a Dockerfile file and it will be searched for in the following order: './Dockerfile-iotmaker', './Dockerfile', './dockerfile', 'Dockerfile.*', 'dockerfile.*', '.*Dockerfile.*' and '.*dockerfile.*'; The repository can be defined by the methods SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(), SetGitCloneToBuildWithPrivateToken() and SetGitCloneToBuildWithUserPassworh(). code: var err error var usr *user.User var userGitConfigPath string var file []byte usr, err = user.Current() if err != nil { panic(err) } userGitConfigPath = filepath.Join(usr.HomeDir, ".gitconfig") file, err = ioutil.ReadFile(userGitConfigPath) var container = ContainerBuilder{} container.SetGitCloneToBuildWithPrivateToken(url, privateToken) container.SetGitConfigFile(string(file))
Português: Define o caminho de um repositório para ser usado como base da imagem a ser montada.
url: Endereço do repositório contendo o projeto privateToken: token definido no portal da sua ferramenta git Nota: Caso o repositório seja privado e o computador hospedeiro tenha acesso ao servidor git, use SetPrivateRepositoryAutoConfig() para copiar as credências do git contidas em ~/.ssh e as configurações de ~/.gitconfig de forma automática; Para conseguir acessar repositórios privados de dentro do container, construa a imagem em duas ou mais etapas e na primeira etapa, copie os arquivos id_rsa e known_hosts para a pasta /root/.ssh e o arquivo .gitconfig para a pasta /root/; A função MakeDefaultDockerfileForMe() monta um dockerfile padrão com os procedimentos acima; Caso a chave ~/.ssh/id_rsa seja protegida com senha, use a função SetGitSshPassword() para definir a senha da mesma; Caso queira definir os arquivos de forma manual, use SetGitConfigFile(), SetSshKnownHostsFile() e SetSshIdRsaFile() para definir os arquivos de forma manual; Esta função deve ser usada com a função ImageBuildFromServer() e SetImageName() para baixar e gerar uma imagem a partir do conteúdo de um repositório git; O repositório deve contar um arquivo Dockerfile e ele será procurado na seguinte ordem: './Dockerfile-iotmaker', './Dockerfile', './dockerfile', 'Dockerfile.*', 'dockerfile.*', '.*Dockerfile.*' e '.*dockerfile.*'; O repositório pode ser definido pelos métodos SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(), SetGitCloneToBuildWithPrivateToken() e SetGitCloneToBuildWithUserPassworh(). code: var err error var usr *user.User var userGitConfigPath string var file []byte usr, err = user.Current() if err != nil { panic(err) } userGitConfigPath = filepath.Join(usr.HomeDir, ".gitconfig") file, err = ioutil.ReadFile(userGitConfigPath) var container = ContainerBuilder{} container.SetGitCloneToBuildWithPrivateToken(url, privateToken) container.SetGitConfigFile(string(file))
func (*ContainerBuilder) SetGitCloneToBuildWithUserPassworh ¶
func (e *ContainerBuilder) SetGitCloneToBuildWithUserPassworh(url, user, password string)
SetGitCloneToBuildWithUserPassworh
English: Defines the path of a repository to be used as the base of the image to be mounted.
url: Address of the repository containing the project user: git user password: git password Note: If the repository is private and the host computer has access to the git server, use SetPrivateRepositoryAutoConfig() to copy the git credentials contained in ~/.ssh and the settings of ~/.gitconfig automatically; To be able to access private repositories from inside the container, build the image in two or more steps and in the first step, copy the id_rsa and known_hosts files to the /root/.ssh folder, and the ~/.gitconfig file to the /root folder; The MakeDefaultDockerfileForMe() function make a standard dockerfile with the procedures above; If the ~/.ssh/id_rsa key is password protected, use the SetGitSshPassword() function to set the password; If you want to define the files manually, use SetGitConfigFile(), SetSshKnownHostsFile() and SetSshIdRsaFile() to define the files manually; This function must be used with the ImageBuildFromServer() and SetImageName() function to download and generate an image from the contents of a git repository; The repository must contain a Dockerfile file and it will be searched for in the following order: './Dockerfile-iotmaker', './Dockerfile', './dockerfile', 'Dockerfile.*', 'dockerfile.*', '.*Dockerfile.*' and '.*dockerfile.*'; The repository can be defined by the methods SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(), SetGitCloneToBuildWithPrivateToken() and SetGitCloneToBuildWithUserPassworh(). code: var err error var usr *user.User var userGitConfigPath string var file []byte usr, err = user.Current() if err != nil { panic(err) } userGitConfigPath = filepath.Join(usr.HomeDir, ".gitconfig") file, err = ioutil.ReadFile(userGitConfigPath) var container = ContainerBuilder{} container.SetGitCloneToBuildWithPrivateToken(url, privateToken) container.SetGitConfigFile(string(file))
Português: Define o caminho de um repositório para ser usado como base da imagem a ser montada.
url: Endereço do repositório contendo o projeto user: git user password: git password Nota: Caso o repositório seja privado e o computador hospedeiro tenha acesso ao servidor git, use SetPrivateRepositoryAutoConfig() para copiar as credências do git contidas em ~/.ssh e as configurações de ~/.gitconfig de forma automática; Para conseguir acessar repositórios privados de dentro do container, construa a imagem em duas ou mais etapas e na primeira etapa, copie os arquivos id_rsa e known_hosts para a pasta /root/.ssh e o arquivo .gitconfig para a pasta /root/; A função MakeDefaultDockerfileForMe() monta um dockerfile padrão com os procedimentos acima; Caso a chave ~/.ssh/id_rsa seja protegida com senha, use a função SetGitSshPassword() para definir a senha da mesma; Caso queira definir os arquivos de forma manual, use SetGitConfigFile(), SetSshKnownHostsFile() e SetSshIdRsaFile() para definir os arquivos de forma manual; Esta função deve ser usada com a função ImageBuildFromServer() e SetImageName() para baixar e gerar uma imagem a partir do conteúdo de um repositório git; O repositório deve contar um arquivo Dockerfile e ele será procurado na seguinte ordem: './Dockerfile-iotmaker', './Dockerfile', './dockerfile', 'Dockerfile.*', 'dockerfile.*', '.*Dockerfile.*' e '.*dockerfile.*'; O repositório pode ser definido pelos métodos SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(), SetGitCloneToBuildWithPrivateToken() e SetGitCloneToBuildWithUserPassworh(). code: var err error var usr *user.User var userGitConfigPath string var file []byte usr, err = user.Current() if err != nil { panic(err) } userGitConfigPath = filepath.Join(usr.HomeDir, ".gitconfig") file, err = ioutil.ReadFile(userGitConfigPath) var container = ContainerBuilder{} container.SetGitCloneToBuildWithPrivateToken(url, privateToken) container.SetGitConfigFile(string(file))
func (*ContainerBuilder) SetGitConfigFile ¶
func (e *ContainerBuilder) SetGitConfigFile(value string)
SetGitConfigFile
English: Defines the contents of the .gitconfig file
var err error var usr *user.User var path string var file []byte usr, err = user.Current() if err != nil { panic(err) } path = filepath.Join(usr.HomeDir, ".gitconfig") file, err = ioutil.ReadFile(path) if err != nil { panic(err) } var container = ContainerBuilder{} container.SetGitConfigFile(string(file))
Português: Define o conteúdo do arquivo .gitconfig
var err error var usr *user.User var path string var file []byte usr, err = user.Current() if err != nil { panic(err) } path = filepath.Join(usr.HomeDir, ".gitconfig") file, err = ioutil.ReadFile(path) if err != nil { panic(err) } var container = ContainerBuilder{} container.SetGitConfigFile(string(file))
func (*ContainerBuilder) SetGitPathPrivateRepository ¶
func (e *ContainerBuilder) SetGitPathPrivateRepository(value string)
SetGitPathPrivateRepository
English: path do private repository defined in "go env -w GOPRIVATE=$GIT_PRIVATE_REPO"
Example: github.com/helmutkemper
Português: caminho do repositório privado definido em "go env -w GOPRIVATE=$GIT_PRIVATE_REPO"
Exemplo: github.com/helmutkemper
func (*ContainerBuilder) SetGitSshPassword ¶
func (e *ContainerBuilder) SetGitSshPassword(password string)
SetGitSshPassword
English: Sets the password for the ssh key for private git repositories.
Note: If the repository is private and the host computer has access to the git server, use SetPrivateRepositoryAutoConfig() to copy the git credentials contained in ~/.ssh and the settings of ~/.gitconfig automatically; To be able to access private repositories from inside the container, build the image in two or more steps and in the first step, copy the id_rsa and known_hosts files to the /root/.ssh folder, and the ~/.gitconfig file to the /root folder; The MakeDefaultDockerfileForMe() function make a standard dockerfile with the procedures above; If the ~/.ssh/id_rsa key is password protected, use the SetGitSshPassword() function to set the password; If you want to define the files manually, use SetGitConfigFile(), SetSshKnownHostsFile() and SetSshIdRsaFile() to define the files manually; This function must be used with the ImageBuildFromServer() and SetImageName() function to download and generate an image from the contents of a git repository; The repository must contain a Dockerfile file and it will be searched for in the following order: './Dockerfile-iotmaker', './Dockerfile', './dockerfile', 'Dockerfile.*', 'dockerfile.*', '.*Dockerfile.*' and '.*dockerfile.*'; The repository can be defined by the methods SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(), SetGitCloneToBuildWithPrivateToken() and SetGitCloneToBuildWithUserPassworh().
Português: Define a senha da chave ssh para repositórios git privados.
Nota: Caso o repositório seja privado e o computador hospedeiro tenha acesso ao servidor git, use SetPrivateRepositoryAutoConfig() para copiar as credências do git contidas em ~/.ssh e as configurações de ~/.gitconfig de forma automática; Para conseguir acessar repositórios privados de dentro do container, construa a imagem em duas ou mais etapas e na primeira etapa, copie os arquivos id_rsa e known_hosts para a pasta /root/.ssh e o arquivo .gitconfig para a pasta /root/; A função MakeDefaultDockerfileForMe() monta um dockerfile padrão com os procedimentos acima; Caso a chave ~/.ssh/id_rsa seja protegida com senha, use a função SetGitSshPassword() para definir a senha da mesma; Caso queira definir os arquivos de forma manual, use SetGitConfigFile(), SetSshKnownHostsFile() e SetSshIdRsaFile() para definir os arquivos de forma manual; Esta função deve ser usada com a função ImageBuildFromServer() e SetImageName() para baixar e gerar uma imagem a partir do conteúdo de um repositório git; O repositório deve contar um arquivo Dockerfile e ele será procurado na seguinte ordem: './Dockerfile-iotmaker', './Dockerfile', './dockerfile', 'Dockerfile.*', 'dockerfile.*', '.*Dockerfile.*' e '.*dockerfile.*'; O repositório pode ser definido pelos métodos SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(), SetGitCloneToBuildWithPrivateToken() e SetGitCloneToBuildWithUserPassworh().
func (*ContainerBuilder) SetImageBuildOptionsCPUPeriod ¶
func (e *ContainerBuilder) SetImageBuildOptionsCPUPeriod(value int64)
SetImageBuildOptionsCPUPeriod
English: Specify the CPU CFS scheduler period, which is used alongside --cpu-quota. Defaults to 100000 microseconds (100 milliseconds). Most users do not change this from the default. For most use-cases, --cpus is a more convenient alternative.
Português: Especifique o período do agendador CFS da CPU, que é usado junto com --cpu-quota. O padrão é 100.000 microssegundos (100 milissegundos). A maioria dos usuários não altera o padrão. Para a maioria dos casos de uso, --cpus é uma alternativa mais conveniente.
func (*ContainerBuilder) SetImageBuildOptionsCPUQuota ¶
func (e *ContainerBuilder) SetImageBuildOptionsCPUQuota(value int64)
SetImageBuildOptionsCPUQuota
English: Set this flag to a value greater or less than the default of 1024 to increase or reduce the container’s weight, and give it access to a greater or lesser proportion of the host machine’s CPU cycles.
This is only enforced when CPU cycles are constrained. When plenty of CPU cycles are available, all containers use as much CPU as they need. In that way, this is a soft limit. --cpu-shares does not prevent containers from being scheduled in swarm mode. It prioritizes container CPU resources for the available CPU cycles. It does not guarantee or reserve any specific CPU access.
Português: Defina este flag para um valor maior ou menor que o padrão de 1024 para aumentar ou reduzir o peso do container e dar a ele acesso a uma proporção maior ou menor dos ciclos de CPU da máquina hospedeira.
Isso só é aplicado quando os ciclos da CPU são restritos. Quando muitos ciclos de CPU estão disponíveis, todos os containeres usam a quantidade de CPU de que precisam. Dessa forma, é um limite flexível. --cpu-shares não impede que os containers sejam agendados no modo swarm. Ele prioriza os recursos da CPU do container para os ciclos de CPU disponíveis. Não garante ou reserva nenhum acesso específico à CPU.
func (*ContainerBuilder) SetImageBuildOptionsCPUSetCPUs ¶
func (e *ContainerBuilder) SetImageBuildOptionsCPUSetCPUs(value string)
SetImageBuildOptionsCPUSetCPUs
English: Limit the specific CPUs or cores a container can use. A comma-separated list or hyphen-separated range of CPUs a container can use, if you have more than one CPU. The first CPU is numbered 0. A valid value might be 0-3 (to use the first, second, third, and fourth CPU) or 1,3 (to use the second and fourth CPU).
Português: Limite a quantidade de CPUs ou núcleos específicos que um container pode usar. Uma lista separada por vírgulas ou intervalo separado por hífen de CPUs que um container pode usar, se você tiver mais de uma CPU. A primeira CPU é numerada como 0. Um valor válido pode ser 0-3 (para usar a primeira, segunda, terceira e quarta CPU) ou 1,3 (para usar a segunda e a quarta CPU).
func (*ContainerBuilder) SetImageBuildOptionsCPUSetMems ¶
func (e *ContainerBuilder) SetImageBuildOptionsCPUSetMems(value string)
SetImageBuildOptionsCPUSetMems
English: Define a memory nodes (MEMs) (--cpuset-mems)
--cpuset-mems="" Memory nodes (MEMs) in which to allow execution (0-3, 0,1). Only effective on NUMA systems.
If you have four memory nodes on your system (0-3), use --cpuset-mems=0,1 then processes in your Docker container will only use memory from the first two memory nodes.
Português: Define memory node (MEMs) (--cpuset-mems)
--cpuset-mems="" Memory nodes (MEMs) no qual permitir a execução (0-3, 0,1). Só funciona em sistemas NUMA.
Se você tiver quatro nodes de memória em seu sistema (0-3), use --cpuset-mems=0,1 então, os processos em seu container do Docker usarão apenas a memória dos dois primeiros nodes.
func (*ContainerBuilder) SetImageBuildOptionsCPUShares ¶
func (e *ContainerBuilder) SetImageBuildOptionsCPUShares(value int64)
SetImageBuildOptionsCPUShares
English: Set this flag to a value greater or less than the default of 1024 to increase or reduce the container’s weight, and give it access to a greater or lesser proportion of the host machine’s CPU cycles. This is only enforced when CPU cycles are constrained. When plenty of CPU cycles are available, all containers use as much CPU as they need. In that way, this is a soft limit. --cpu-shares does not prevent containers from being scheduled in swarm mode. It prioritizes container CPU resources for the available CPU cycles. It does not guarantee or reserve any specific CPU access.
Português: Defina este sinalizador para um valor maior ou menor que o padrão de 1024 para aumentar ou reduzir o peso do container e dar a ele acesso a uma proporção maior ou menor dos ciclos de CPU da máquina host. Isso só é aplicado quando os ciclos da CPU são restritos. Quando muitos ciclos de CPU estão disponíveis, todos os container usam a quantidade de CPU de que precisam. Dessa forma, este é um limite flexível. --cpu-shares não impede que os containers sejam agendados no modo swarm. Ele prioriza os recursos da CPU do container para os ciclos de CPU disponíveis. Não garante ou reserva nenhum acesso específico à CPU.
func (*ContainerBuilder) SetImageBuildOptionsCacheFrom ¶
func (e *ContainerBuilder) SetImageBuildOptionsCacheFrom(values []string)
SetImageBuildOptionsCacheFrom
English: specifies images that are used for matching cache. Images specified here do not need to have a valid parent chain to match cache.
Português: especifica imagens que são usadas para correspondência de cache. As imagens especificadas aqui não precisam ter uma cadeia pai válida para corresponder a cache.
func (*ContainerBuilder) SetImageBuildOptionsExtraHosts ¶
func (e *ContainerBuilder) SetImageBuildOptionsExtraHosts(values []string)
SetImageBuildOptionsExtraHosts
English: Add hostname mappings at build-time. Use the same values as the docker client --add-host parameter.
values: somehost:162.242.195.82 otherhost:50.31.209.229 An entry with the ip address and hostname is created in /etc/hosts inside containers for this build, e.g: 162.242.195.82 somehost 50.31.209.229 otherhost
Português): Adiciona itens ao mapa de hostname durante o processo de construção da imagem. Use os mesmos valores que em docker client --add-host parameter.
values: somehost:162.242.195.82 otherhost:50.31.209.229 Uma nova entrada com o endereço ip e hostname será criada dentro de /etc/hosts do container. Exemplo: 162.242.195.82 somehost 50.31.209.229 otherhost
func (*ContainerBuilder) SetImageBuildOptionsIsolationDefault ¶
func (e *ContainerBuilder) SetImageBuildOptionsIsolationDefault()
SetImageBuildOptionsIsolationDefault
English: Set default isolation mode on current daemon
Português: Define o método de isolamento do processo como sendo o mesmo do deamon
func (*ContainerBuilder) SetImageBuildOptionsIsolationHyperV ¶
func (e *ContainerBuilder) SetImageBuildOptionsIsolationHyperV()
SetImageBuildOptionsIsolationHyperV
English: Set HyperV isolation mode
Português: Define o método de isolamento como sendo HyperV
func (*ContainerBuilder) SetImageBuildOptionsIsolationProcess ¶
func (e *ContainerBuilder) SetImageBuildOptionsIsolationProcess()
SetImageBuildOptionsIsolationProcess
English: Set process isolation mode
Português: Determina o método de isolamento do processo
func (*ContainerBuilder) SetImageBuildOptionsMemory ¶
func (e *ContainerBuilder) SetImageBuildOptionsMemory(value int64)
SetImageBuildOptionsMemory
English: The maximum amount of memory the container can use. If you set this option, the minimum allowed value is 4 * 1024 * 1024 (4 megabyte).
Use value * KKiloByte, value * KMegaByte and value * KGigaByte See https://docs.docker.com/engine/reference/run/#user-memory-constraints
Português: Memória máxima total que o container pode usar. Se você vai usar esta opção, o máximo permitido é 4 * 1024 * 1024 (4 megabyte)
Use value * KKiloByte, value * KMegaByte e value * KGigaByte See https://docs.docker.com/engine/reference/run/#user-memory-constraints
func (*ContainerBuilder) SetImageBuildOptionsMemorySwap ¶
func (e *ContainerBuilder) SetImageBuildOptionsMemorySwap(value int64)
SetImageBuildOptionsMemorySwap
English: Set memory swap (--memory-swap)
Use value * KKiloByte, value * KMegaByte and value * KGigaByte See https://docs.docker.com/engine/reference/run/#user-memory-constraints
Português: habilita a opção memory swp
Use value * KKiloByte, value * KMegaByte e value * KGigaByte See https://docs.docker.com/engine/reference/run/#user-memory-constraints
func (*ContainerBuilder) SetImageBuildOptionsNoCache ¶
func (e *ContainerBuilder) SetImageBuildOptionsNoCache()
SetImageBuildOptionsNoCache
English: Set image build no cache
Português: Define a opção `sem cache` para a construção da imagem
func (*ContainerBuilder) SetImageBuildOptionsPlatform ¶
func (e *ContainerBuilder) SetImageBuildOptionsPlatform(value string)
SetImageBuildOptionsPlatform
English: Target platform containers for this service will run on, using the os[/arch[/variant]] syntax, e.g.
osx windows/amd64 linux/arm64/v8
Português: Especifica a plataforma de container onde o serviço vai rodar, usando a sintaxe os[/arch[/variant]]
osx windows/amd64 linux/arm64/v8
func (*ContainerBuilder) SetImageBuildOptionsSecurityOpt ¶
func (e *ContainerBuilder) SetImageBuildOptionsSecurityOpt(value []string)
SetImageBuildOptionsSecurityOpt
English: Set the container security options
label=user:USER — Set the label user for the container label=role:ROLE — Set the label role for the container label=type:TYPE — Set the label type for the container label=level:LEVEL — Set the label level for the container label=disable — Turn off label confinement for the container apparmor=PROFILE — Set the apparmor profile to be applied to the container no-new-privileges:true — Disable container processes from gaining new privileges seccomp=unconfined — Turn off seccomp confinement for the container seccomp=profile.json — White-listed syscalls seccomp Json file to be used as a seccomp filter
Português: Modifica as opções de segurança do container
label=user:USER — Determina o rótulo user para o container label=role:ROLE — Determina o rótulo role para o container label=type:TYPE — Determina o rótulo type para o container label=level:LEVEL — Determina o rótulo level para o container label=disable — Desliga o confinamento do rótulo para o container apparmor=PROFILE — Habilita o perfil definido pelo apparmor do linux para ser definido ao container no-new-privileges:true — Impede o processo do container a ganhar novos privilégios seccomp=unconfined — Desliga o confinamento causado pelo seccomp do linux ao container seccomp=profile.json — White-listed syscalls seccomp Json file to be used as a seccomp filter
func (*ContainerBuilder) SetImageBuildOptionsSquash ¶
func (e *ContainerBuilder) SetImageBuildOptionsSquash(value bool)
SetImageBuildOptionsSquash
English: squash the resulting image's layers to the parent preserves the original image and creates a new one from the parent with all the changes applied to a single layer
Português: Usa o conteúdo dos layers da imagem pai para criar uma imagem nova, preservando a imagem pai, e aplica todas as mudanças a um novo layer
func (*ContainerBuilder) SetImageBuildOptionsTarget ¶
func (e *ContainerBuilder) SetImageBuildOptionsTarget(value string)
SetImageBuildOptionsTarget
English: Build the specified stage as defined inside the Dockerfile. See the multi-stage build docs for details.
See https://docs.docker.com/develop/develop-images/multistage-build/
Português: Monta o container a partir do estágio definido no arquivo Dockerfile. Veja a documentação de múltiplos estágios para mais detalhes.
See https://docs.docker.com/develop/develop-images/multistage-build/
func (*ContainerBuilder) SetImageName ¶
func (e *ContainerBuilder) SetImageName(value string)
SetImageName
English: Defines the name of the image to be used or created
value: name of the image to be downloaded or created Note: the image name must have the version tag
Português: Define o nome da imagem a ser usada ou criada
value: noma da imagem a ser baixada ou criada Nota: o nome da imagem deve ter a tag de versão
func (*ContainerBuilder) SetInspectInterval ¶
func (e *ContainerBuilder) SetInspectInterval(value time.Duration)
SetInspectInterval
English: Defines the container's monitoring interval [optional]
value: time interval between container inspection events Note: This function has a high computational cost and should be used sparingly. The captured values are presented by GetLastInspect() and GetChannelOnContainerInspect()
Português: Define o intervalo de monitoramento do container [opcional]
value: intervalo de tempo entre os eventos de inspeção do container Nota: Esta função tem um custo computacional elevado e deve ser usada com moderação. Os valores capturados são apresentados por GetLastInspect() e GetChannelOnContainerInspect()
func (*ContainerBuilder) SetNetworkDocker ¶
func (e *ContainerBuilder) SetNetworkDocker(network isolatedNetwork.ContainerBuilderNetworkInterface)
SetNetworkDocker
English: Sets the docker network manager pointer
network: pointer to the network manager object. Note: compatible with dockerBuilderNetwork.ContainerBuilderNetwork{} object
Português: Define o ponteiro do gerenciador de rede docker
network: ponteiro para o objeto gerenciador de rede. Nota: compatível com o objeto dockerBuilderNetwork.ContainerBuilderNetwork{}
Example ¶
var err error var netDocker = dockerNetwork.ContainerBuilderNetwork{} err = netDocker.Init() if err != nil { panic(err) } // create a network named cache_delete_after_test, subnet 10.0.0.0/16 e gatway 10.0.0.1 err = netDocker.NetworkCreate("cache_delete_after_test", "10.0.0.0/16", "10.0.0.1") if err != nil { panic(err) } // At this point in the code, the network has been created and is ready for use var mongoDocker = &ContainerBuilder{} // set a docker network mongoDocker.SetNetworkDocker(&netDocker) // set an image name mongoDocker.SetImageName("mongo:latest") // set a container name mongoDocker.SetContainerName("container_delete_mongo_after_test") // set a port to expose mongoDocker.AddPortToExpose("27017") // se a environment var list mongoDocker.SetEnvironmentVar( []string{ "--host 0.0.0.0", }, ) // set a MongoDB data dir to ./test/data err = mongoDocker.AddFileOrFolderToLinkBetweenConputerHostAndContainer("./test/data", "/data") if err != nil { panic(err) } // set a text indicating for container ready for use mongoDocker.SetWaitStringWithTimeout(`"msg":"Waiting for connections","attr":{"port":27017`, 20*time.Second) // inicialize the object before sets err = mongoDocker.Init() if err != nil { panic(err) } // build a container err = mongoDocker.ContainerBuildFromImage() if err != nil { panic(err) } // At this point, the MongoDB is ready for use on port 27017 // Stop and delete the container GarbageCollector()
Output:
func (*ContainerBuilder) SetOpenAllContainersPorts ¶
func (e *ContainerBuilder) SetOpenAllContainersPorts()
SetOpenAllContainersPorts
English: Automatically exposes all ports listed in the image used to generate the container
Note: The ports exposed in the creation of the container can be defined by SetOpenAllContainersPorts(), AddPortToChange() and AddPortToExpose(); By default, all doors are closed; The ImageListExposedPorts() function returns all ports defined in the image to be exposed.
Português: Expõe automaticamente todas as portas listadas na imagem usada para gerar o container
Nota: As portas expostas na criação do container pode ser definidas por SetOpenAllContainersPorts(), AddPortToChange() e AddPortToExpose(); Por padrão, todas as portas ficam fechadas; A função ImageListExposedPorts() retorna todas as portas definidas na imagem para serem expostas.
func (*ContainerBuilder) SetPrintBuildOnStrOut ¶ added in v0.5.10
func (e *ContainerBuilder) SetPrintBuildOnStrOut()
SetPrintBuildOnStrOut
English: Prints the standard output used when building the image or the container to the standard output of the log.
Português: Imprime a saída padrão usada durante a construção da imagem ou do container no log.
func (*ContainerBuilder) SetPrivateRepositoryAutoConfig ¶
func (e *ContainerBuilder) SetPrivateRepositoryAutoConfig() (err error)
SetPrivateRepositoryAutoConfig
English: Copies the ssh ~/.ssh/id_rsa file and the ~/.gitconfig file to the SSH_ID_RSA_FILE and GITCONFIG_FILE variables.
Português: Copia o arquivo ssh ~/.ssh/id_rsa e o arquivo ~/.gitconfig para as variáveis SSH_ID_RSA_FILE e GITCONFIG_FILE.
func (*ContainerBuilder) SetSshIdRsaFile ¶
func (e *ContainerBuilder) SetSshIdRsaFile(value string)
SetSshIdRsaFile
English: Set a id_rsa file from shh
var err error var usr *user.User var path string var file []byte usr, err = user.Current() if err != nil { panic(err) } path = filepath.Join(usr.HomeDir, ".ssh", "id_rsa") file, err = ioutil.ReadFile(path) if err != nil { panic(err) } var container = ContainerBuilder{} container.SetSshIdRsaFile(string(file))
Português: Define o arquivo id_rsa do shh
var err error var usr *user.User var path string var file []byte usr, err = user.Current() if err != nil { panic(err) } path = filepath.Join(usr.HomeDir, ".ssh", "id_rsa") file, err = ioutil.ReadFile(path) if err != nil { panic(err) } var container = ContainerBuilder{} container.SetSshIdRsaFile(string(file))
func (*ContainerBuilder) SetSshKnownHostsFile ¶
func (e *ContainerBuilder) SetSshKnownHostsFile(value string)
SetSshKnownHostsFile
English: set a sseh knownhosts file
var err error var usr *user.User var path string var file []byte usr, err = user.Current() if err != nil { panic(err) } path = filepath.Join(usr.HomeDir, ".ssh", "known_hosts") file, err = ioutil.ReadFile(path) if err != nil { panic(err) } var container = ContainerBuilder{} container.SetSshKnownHostsFile(string(file))
Português: define o arquivo knownhosts do ssh
var err error var usr *user.User var path string var file []byte usr, err = user.Current() if err != nil { panic(err) } path = filepath.Join(usr.HomeDir, ".ssh", "known_hosts") file, err = ioutil.ReadFile(path) if err != nil { panic(err) } var container = ContainerBuilder{} container.SetSshKnownHostsFile(string(file))
func (*ContainerBuilder) SetWaitString ¶
func (e *ContainerBuilder) SetWaitString(value string)
SetWaitString
English: Defines a text to be searched for in the container's default output and forces it to wait for the container to be considered ready-to-use
value: searched text
Português: Define um texto a ser procurado na saída padrão do container e força a espera do mesmo para se considerar o container como pronto para uso
value: texto procurado
func (*ContainerBuilder) SetWaitStringWithTimeout ¶
func (e *ContainerBuilder) SetWaitStringWithTimeout(value string, timeout time.Duration)
SetWaitStringWithTimeout
English: Defines a text to be searched for in the container's default output and forces it to wait for the container to be considered ready-to-use
value: text emitted to default output reporting by an expected event timeout: maximum waiting time
Português: Define um texto a ser procurado na saída padrão do container e força a espera do mesmo para se considerar o container como pronto para uso
value: texto emitido na saída padrão informando por um evento esperado timeout: tempo máximo de espera
func (*ContainerBuilder) WaitForTextInContainerLog ¶
func (e *ContainerBuilder) WaitForTextInContainerLog(value string) (dockerLogs string, err error)
WaitForTextInContainerLog
English: Wait for the text to appear in the container's default output
value: searched text
Português: Espera pelo texto aparecer na saída padrão do container
value: texto procurado
func (*ContainerBuilder) WaitForTextInContainerLogWithTimeout ¶
func (e *ContainerBuilder) WaitForTextInContainerLogWithTimeout(value string, timeout time.Duration) (dockerLogs string, err error)
WaitForTextInContainerLogWithTimeout
English: Wait for the text to appear in the container's default output
value: searched text timeout: wait timeout
Português: Espera pelo texto aparecer na saída padrão do container
value: texto procurado timeout: tempo limite de espera
type DockerfileAuto ¶
type DockerfileAuto interface { MountDefaultDockerfile(args map[string]*string, changePorts []dockerfileGolang.ChangePort, openPorts, exposePorts []string, volumes []mount.Mount, useCache bool) (dockerfile string, err error) Prayer() }
DockerfileAuto
English: Interface from automatic Dockerfile generator.
Note: To be able to access private repositories from inside the container, build the image in two or more steps and in the first step, copy the id_rsa and known_hosts files to the /root/.ssh folder and the .gitconfig file to the /root folder. One way to do this automatically is to use the Dockerfile example below, where the arguments SSH_ID_RSA_FILE contains the file ~/.ssh/id_rsa, KNOWN_HOSTS_FILE contains the file ~/.ssh/known_hosts and GITCONFIG_FILE contains the file ~/.gitconfig. If the ~/.ssh/id_rsa key is password protected, use the SetGitSshPassword() function to set the password. If you want to copy the files into the image automatically, use SetPrivateRepositoryAutoConfig() and the function will copy the files ~/.ssh/id_rsa, ~/.ssh/known_hosts and ~/.gitconfig to the viable arguments located above. If you want to define the files manually, use SetGitConfigFile(), SetSshKnownHostsFile() and SetSshIdRsaFile() to define the files manually. The Dockerfile below can be used as a base # (en) first stage of the process # (pt) primeira etapa do processo FROM golang:1.16-alpine as builder # (en) enable the argument variables # (pt) habilita as variáveis de argumento ARG SSH_ID_RSA_FILE ARG KNOWN_HOSTS_FILE ARG GITCONFIG_FILE ARG GIT_PRIVATE_REPO # (en) creates the .ssh directory within the root directory # (pt) cria o diretório .ssh dentro do diretório root RUN mkdir -p /root/.ssh/ && \ # (en) creates the id_esa file inside the .ssh directory # (pt) cria o arquivo id_esa dentro do diretório .ssh echo "$SSH_ID_RSA_FILE" > /root/.ssh/id_rsa && \ # (en) adjust file access security # (pt) ajusta a segurança de acesso do arquivo chmod -R 600 /root/.ssh/ && \ # (en) creates the known_hosts file inside the .ssh directory # (pt) cria o arquivo known_hosts dentro do diretório .ssh echo "$KNOWN_HOSTS_FILE" > /root/.ssh/known_hosts && \ # (en) adjust file access security # (pt) ajusta a segurança de acesso do arquivo chmod -R 600 /root/.ssh/known_hosts && \ # (en) creates the .gitconfig file at the root of the root directory # (pt) cria o arquivo .gitconfig na raiz do diretório /root echo "$GITCONFIG_FILE" > /root/.gitconfig && \ # (en) adjust file access security # (pt) ajusta a segurança de acesso do arquivo chmod -R 600 /root/.gitconfig && \ # (en) prepares the OS for installation # (pt) prepara o OS para instalação apk update && \ # (en) install git and openssh # (pt) instala o git e o opnssh apk add --no-cache build-base git openssh && \ # (en) clear the cache # (pt) limpa a cache rm -rf /var/cache/apk/* # (en) creates the /app directory, where your code will be installed # (pt) cria o diretório /app, onde seu código vai ser instalado WORKDIR /app # (en) copy your project into the /app folder # (pt) copia seu projeto para dentro da pasta /app COPY . . # (en) enables the golang compiler to run on an extremely simple OS, scratch # (pt) habilita o compilador do golang para rodar em um OS extremamente simples, o scratch ARG CGO_ENABLED=0 # (en) adjust git to work with shh # (pt) ajusta o git para funcionar com shh RUN git config --global url.ssh://git@github.com/.insteadOf https://github.com/ # (en) defines the path of the private repository # (pt) define o caminho do repositório privado RUN echo "go env -w GOPRIVATE=$GIT_PRIVATE_REPO" # (en) install the dependencies in the go.mod file # (pt) instala as dependências no arquivo go.mod RUN go mod tidy # (en) compiles the main.go file # (pt) compila o arquivo main.go RUN go build -ldflags="-w -s" -o /app/main /app/main.go # (en) creates a new scratch-based image # (pt) cria uma nova imagem baseada no scratch # (en) scratch is an extremely simple OS capable of generating very small images # (pt) o scratch é um OS extremamente simples capaz de gerar imagens muito reduzidas # (en) discarding the previous image erases git access credentials for your security and reduces the size of the # image to save server space # (pt) descartar a imagem anterior apaga as credenciais de acesso ao git para a sua segurança e reduz o tamanho # da imagem para poupar espaço no servidor FROM scratch # (en) copy your project to the new image # (pt) copia o seu projeto para a nova imagem COPY --from=builder /app/main . # (en) execute your project # (pt) executa o seu projeto CMD ["/main"]
Português: Interface do gerador de dockerfile automático.
Nota: Para conseguir acessar repositórios privados de dentro do container, construa a imagem em duas ou mais etapas e na primeira etapa, copie os arquivos id_rsa e known_hosts para a pasta /root/.ssh e o arquivo .gitconfig para a pasta /root/. Uma maneira de fazer isto de forma automática é usar o exemplo de Dockerfile abaixo, onde os argumentos SSH_ID_RSA_FILE contém o arquivo ~/.ssh/id_rsa, KNOWN_HOSTS_FILE contém o arquivo ~/.ssh/known_hosts e GITCONFIG_FILE contém o arquivo ~/.gitconfig. Caso a chave ~/.ssh/id_rsa seja protegida com senha, use a função SetGitSshPassword() para definir a senha da mesma. Caso você queira copiar os arquivos para dentro da imagem de forma automática, use SetPrivateRepositoryAutoConfig() e a função copiará os arquivos ~/.ssh/id_rsa, ~/.ssh/known_hosts e ~/.gitconfig para as viáveis de argumentos sitada anteriormente. Caso queira definir os arquivos de forma manual, use SetGitConfigFile(), SetSshKnownHostsFile() e SetSshIdRsaFile() para definir os arquivos de forma manual. O arquivo Dockerfile abaixo pode ser usado como base # (en) first stage of the process # (pt) primeira etapa do processo FROM golang:1.16-alpine as builder # (en) enable the argument variables # (pt) habilita as variáveis de argumento ARG SSH_ID_RSA_FILE ARG KNOWN_HOSTS_FILE ARG GITCONFIG_FILE ARG GIT_PRIVATE_REPO # (en) creates the .ssh directory within the root directory # (pt) cria o diretório .ssh dentro do diretório root RUN mkdir -p /root/.ssh/ && \ # (en) creates the id_esa file inside the .ssh directory # (pt) cria o arquivo id_esa dentro do diretório .ssh echo "$SSH_ID_RSA_FILE" > /root/.ssh/id_rsa && \ # (en) adjust file access security # (pt) ajusta a segurança de acesso do arquivo chmod -R 600 /root/.ssh/ && \ # (en) creates the known_hosts file inside the .ssh directory # (pt) cria o arquivo known_hosts dentro do diretório .ssh echo "$KNOWN_HOSTS_FILE" > /root/.ssh/known_hosts && \ # (en) adjust file access security # (pt) ajusta a segurança de acesso do arquivo chmod -R 600 /root/.ssh/known_hosts && \ # (en) creates the .gitconfig file at the root of the root directory # (pt) cria o arquivo .gitconfig na raiz do diretório /root echo "$GITCONFIG_FILE" > /root/.gitconfig && \ # (en) adjust file access security # (pt) ajusta a segurança de acesso do arquivo chmod -R 600 /root/.gitconfig && \ # (en) prepares the OS for installation # (pt) prepara o OS para instalação apk update && \ # (en) install git and openssh # (pt) instala o git e o opnssh apk add --no-cache build-base git openssh && \ # (en) clear the cache # (pt) limpa a cache rm -rf /var/cache/apk/* # (en) creates the /app directory, where your code will be installed # (pt) cria o diretório /app, onde seu código vai ser instalado WORKDIR /app # (en) copy your project into the /app folder # (pt) copia seu projeto para dentro da pasta /app COPY . . # (en) enables the golang compiler to run on an extremely simple OS, scratch # (pt) habilita o compilador do golang para rodar em um OS extremamente simples, o scratch ARG CGO_ENABLED=0 # (en) adjust git to work with shh # (pt) ajusta o git para funcionar com shh RUN git config --global url.ssh://git@github.com/.insteadOf https://github.com/ # (en) defines the path of the private repository # (pt) define o caminho do repositório privado RUN echo "go env -w GOPRIVATE=$GIT_PRIVATE_REPO" # (en) install the dependencies in the go.mod file # (pt) instala as dependências no arquivo go.mod RUN go mod tidy # (en) compiles the main.go file # (pt) compila o arquivo main.go RUN go build -ldflags="-w -s" -o /app/main /app/main.go # (en) creates a new scratch-based image # (pt) cria uma nova imagem baseada no scratch # (en) scratch is an extremely simple OS capable of generating very small images # (pt) o scratch é um OS extremamente simples capaz de gerar imagens muito reduzidas # (en) discarding the previous image erases git access credentials for your security and reduces the size of the # image to save server space # (pt) descartar a imagem anterior apaga as credenciais de acesso ao git para a sua segurança e reduz o tamanho # da imagem para poupar espaço no servidor FROM scratch # (en) copy your project to the new image # (pt) copia o seu projeto para a nova imagem COPY --from=builder /app/main . # (en) execute your project # (pt) executa o seu projeto CMD ["/main"]
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
English: holds configuration settings for the HEALTHCHECK feature.
Português: contém as configurações para o HEALTHCHECK
type NetworkChaos ¶ added in v0.5.40
type NetworkChaos struct {
// contains filtered or unexported fields
}
func (*NetworkChaos) Init ¶ added in v0.5.40
func (e *NetworkChaos) Init() (err error)
Example ¶
package main import ( "context" "fmt" dockerNetwork "github.com/helmutkemper/iotmaker.docker.builder.network" "github.com/helmutkemper/util" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/mongo/readpref" "log" "time" ) func main() { var err error GarbageCollector() var netDocker = &dockerNetwork.ContainerBuilderNetwork{} err = netDocker.Init() if err != nil { util.TraceToLog() panic(err) } err = netDocker.NetworkCreate("cache_delete_after_test", "10.0.0.0/16", "10.0.0.1") if err != nil { util.TraceToLog() panic(err) } var mongoDocker = &ContainerBuilder{} mongoDocker.SetNetworkDocker(netDocker) mongoDocker.SetImageName("mongo:latest") mongoDocker.SetContainerName("container_delete_mongo_after_test") //mongoDocker.AddPortToChange("27017", "27016") //mongoDocker.AddPortToExpose("27017") mongoDocker.SetEnvironmentVar( []string{ "--bind_ip_all", "--host 0.0.0.0", "--bind 0.0.0.0", }, ) mongoDocker.SetWaitStringWithTimeout(`"msg":"Waiting for connections","attr":{"port":27017`, 20*time.Second) err = mongoDocker.Init() if err != nil { util.TraceToLog() panic(err) } err = mongoDocker.ContainerBuildFromImage() if err != nil { util.TraceToLog() panic(err) } var redis = ContainerBuilder{} redis.SetNetworkDocker(netDocker) redis.SetImageName("redis:latest") redis.SetContainerName("container_delete_redis_test") redis.AddPortToExpose("6379") redis.SetWaitStringWithTimeout("Ready to accept connections", 10*time.Second) err = redis.Init() if err != nil { util.TraceToLog() panic(err) } err = redis.ContainerBuildFromImage() if err != nil { util.TraceToLog() panic(err) } var chaos = NetworkChaos{} chaos.SetNetworkDocker(netDocker) chaos.SetFatherContainer(mongoDocker) chaos.SetPorts(27017, 27016, false) err = chaos.Init() if err != nil { util.TraceToLog() panic(err) } err = testNetworkOverloaded( "mongodb://0.0.0.0:27016", 2*time.Second, ) if err != nil { util.TraceToLog() panic(err) } } // testNetworkOverloaded (English): Tests the new network port // testNetworkOverloaded (Português): Testa a nova porta de rede func testNetworkOverloaded( address string, timeout time.Duration, ) ( err error, ) { // (English): Runtime measurement starts // (Português): Começa a medição do tempo de execução start := time.Now() var mongoClient *mongo.Client var cancel context.CancelFunc var ctx context.Context // (English): Prepare the MongoDB client // (Português): Prepara o cliente do MongoDB mongoClient, err = mongo.NewClient(options.Client().ApplyURI(address)) if err != nil { return } // (English): Connects to MongoDB // (Português): Conecta ao MongoDB err = mongoClient.Connect(ctx) if err != nil { return } // (English): Prepares the timeout // (Português): Prepara o tempo limite ctx, cancel = context.WithTimeout(context.Background(), timeout) defer cancel() // (English): Ping() to test the MongoDB connection // (Português): Faz um ping() para testar a conexão do MongoDB err = mongoClient.Ping(ctx, readpref.Primary()) if err != nil { return } // (English): New collection format // (Português): Formato da nova coleção type Trainer struct { Name string Age int City string } // (English): Creates the 'test' bank and the 'dinos' collection // (Português): Cria o banco 'test' e a coleção 'dinos' collection := mongoClient.Database("test").Collection("dinos") // (English): Prepares the data to be inserted // (Português): Prepara os dados a serem inseridos trainerData := Trainer{"T-Rex", 10, "Jurassic Town"} for i := 0; i != 100; i += 1 { // (English): Insert the data // (Português): Insere os dados _, err = collection.InsertOne(context.TODO(), trainerData) if err != nil { log.Printf("collection.InsertOne().error: %v", err) return } } // (English): Stop the operation time measurement // (Português): Para a medição de tempo da operação duration := time.Since(start) fmt.Printf("End!\n") fmt.Printf("Duration: %v\n\n", duration) return }
Output:
func (*NetworkChaos) SetContainerName ¶ added in v0.5.40
func (e *NetworkChaos) SetContainerName(value string)
func (*NetworkChaos) SetFatherContainer ¶ added in v0.5.40
func (e *NetworkChaos) SetFatherContainer(fatherContainer *ContainerBuilder)
func (*NetworkChaos) SetNetworkDocker ¶ added in v0.5.40
func (e *NetworkChaos) SetNetworkDocker(network isolatedNetwork.ContainerBuilderNetworkInterface)
SetNetworkDocker (english):
SetNetworkDocker (português): Define o ponteiro do gerenciador de rede docker
Entrada: network: ponteiro para o objeto gerenciador de rede. Nota: - A entrada network deve ser compatível com a interface dockerBuilderNetwork.ContainerBuilderNetwork{}
func (*NetworkChaos) SetPorts ¶ added in v0.5.40
func (e *NetworkChaos) SetPorts(listenPort, outputPort int, invert bool)
Source Files ¶
- conts.go
- doc.go
- funcAddFiileOrFolderToLinkBetweenConputerHostAndContainer.go
- funcAddImageBuildOptionsBuildArgs.go
- funcAddImageBuildOptionsGitCredentials.go
- funcAddPortToChange.go
- funcAddPortToDockerfileExpose.go
- funcAddPortToOpen.go
- funcContainerBuildFromImage.go
- funcContainerFindIdByName.go
- funcContainerFindIdByNameContains.go
- funcContainerInspect.go
- funcContainerPause.go
- funcContainerRemove.go
- funcContainerStart.go
- funcContainerStop.go
- funcFindCurrentIPV4Address.go
- funcFindCurrentIPV4AddressSupport.go
- funcFindTextInsideContainerLog.go
- funcGarbageCollector.go
- funcGetChannelEvent.go
- funcGetChannelOnContainerInspect.go
- funcGetChannelOnContainerReady.go
- funcGetContainerID.go
- funcGetContainerLog.go
- funcGetIdByContainerName.go
- funcGetImageID.go
- funcGetImageName.go
- funcGetIpAddress.go
- funcGetLastInspect.go
- funcGetLastLogs.go
- funcGetNetworkGatewayIPV4.go
- funcGetNetworkGatewayIPV4ByNetworkName.go
- funcGetNetworkIPV4.go
- funcGetNetworkIPV4ByNetworkName.go
- funcGetNetworkInterface.go
- funcGitMakePublicSshKey.go
- funcImageBuildFromFolder.go
- funcImageBuildFromServer.go
- funcImageFindIdByName.go
- funcImageFindIdByNameContains.go
- funcImageListExposedPorts.go
- funcImageListExposedVolumes.go
- funcImagePull.go
- funcImageRemove.go
- funcImageRemoveByName.go
- funcIncIpV4Address.go
- funcInit.go
- funcMakeDefaultGolangDockerfileForMe.go
- funcRemoveAllByNameContains.go
- funcSetBuildFolderPath.go
- funcSetCacheEnable.go
- funcSetContainerAttachStandardStreamsToTty.go
- funcSetContainerCommandToRunWhenStartingTheContainer.go
- funcSetContainerEntrypointToRunWhenStartingTheContainer.go
- funcSetContainerHealthcheck.go
- funcSetContainerName.go
- funcSetContainerRestartPolicyAlways.go
- funcSetContainerRestartPolicyNo.go
- funcSetContainerRestartPolicyOnFailure.go
- funcSetContainerRestartPolicyUnlessStopped.go
- funcSetContainerShellForShellFormOfRunCmdEntrypoint.go
- funcSetDoNotOpenContainersPorts.go
- funcSetDockerfileBuilder.go
- funcSetEnvironmentVar.go
- funcSetGitCloneToBuild.go
- funcSetGitCloneToBuildWithPrivateSshKey.go
- funcSetGitCloneToBuildWithPrivateToken.go
- funcSetGitCloneToBuildWithUserPassworh.go
- funcSetGitConfigFile.go
- funcSetGitPathPrivateRepository.go
- funcSetGitSshPassword.go
- funcSetImageBuildOptionsCPUPeriod.go
- funcSetImageBuildOptionsCPUQuota.go
- funcSetImageBuildOptionsCPUSetCPUs.go
- funcSetImageBuildOptionsCPUSetMems.go
- funcSetImageBuildOptionsCPUShares.go
- funcSetImageBuildOptionsCacheFrom.go
- funcSetImageBuildOptionsExtraHosts.go
- funcSetImageBuildOptionsIsolationDefault.go
- funcSetImageBuildOptionsIsolationHyperV.go
- funcSetImageBuildOptionsIsolationProcess.go
- funcSetImageBuildOptionsMemory.go
- funcSetImageBuildOptionsMemorySwap.go
- funcSetImageBuildOptionsNoCache.go
- funcSetImageBuildOptionsPlatform.go
- funcSetImageBuildOptionsSecurityOpt.go
- funcSetImageBuildOptionsSquash.go
- funcSetImageBuildOptionsTarget.go
- funcSetImageName.go
- funcSetInspectInterval.go
- funcSetNetworkDocker.go
- funcSetPrintBuildOnStrOut.go
- funcSetPrivateRepositoryAutoConfig.go
- funcSetSshIdRsaFile.go
- funcSetSshKnownHostsFile.go
- funcSetWaitString.go
- funcSetWaitStringWithTimeout.go
- funcVerifyImageName.go
- funcWaitForTextInContainerLog.go
- funcWaitForTextInContainerLogWithTimeout.go
- typeContainerBuilder.go
- typeDockerfileAuto.go
- typeGitData.go
- typeHealthConfig.go
- typeNameAndId.go
- typeNetworkChaos.go