Documentation ¶
Overview ¶
Package iotmakerdockerbuilder (english):
Package iotmakerdockerbuilder (português):
Index ¶
- Constants
- func GarbageCollector()
- type ContainerBuilder
- func (e *ContainerBuilder) AddFiileOrFolderToLinkBetweenConputerHostAndContainer(computerHostPath, insideContainerPath string) (err error)
- func (e *ContainerBuilder) AddImageBuildOptionsBuildArgs(key string, value *string)
- func (e *ContainerBuilder) AddPortToChange(imagePort string, newPort string)
- func (e *ContainerBuilder) AddPortToOpen(value string)
- func (e *ContainerBuilder) ContainerBuildFromImage() (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) 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) Prayer()
- func (e *ContainerBuilder) RemoveAllByNameContains(value string) (err error)
- func (e *ContainerBuilder) SetBuildFolderPath(value string)
- 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) 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(value bool)
- 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) 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 Overloading
Examples ¶
- ContainerBuilder.AddFiileOrFolderToLinkBetweenConputerHostAndContainer
- ContainerBuilder.AddPortToChange
- ContainerBuilder.AddPortToOpen
- ContainerBuilder.ContainerBuildFromImage
- ContainerBuilder.FindCurrentIPV4Address
- ContainerBuilder.ImageBuildFromFolder
- ContainerBuilder.ImageListExposedPorts
- ContainerBuilder.ImageListExposedVolumes
- ContainerBuilder.ImagePull
- ContainerBuilder.SetGitCloneToBuild
- ContainerBuilder.SetGitPathPrivateRepository
- ContainerBuilder.SetNetworkDocker
- Overloading.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): All tests use networks, containers and images with the term "delete" contained in the name.
This function considers that the test is over and that these elements must be removed at the end of each test, and as a guarantee, if any test has failed, it is also used before each test.
GarbageCollector (português): Todos os testes usam redes, containers e imagens com o termo "delete" contido no nome.
Esta função considera que o teste acabou e que estes elementos devem ser removidos ao final de cada teste, e por garantia, caso algum teste tenha falhado, também é usada antes de cada teste.
Types ¶
type ContainerBuilder ¶
type ContainerBuilder struct { IPV4Address string // contains filtered or unexported fields }
ContainerBuilder (english):
ContainerBuilder (português): Gerenciador de containers e imagens docker
func (*ContainerBuilder) AddFiileOrFolderToLinkBetweenConputerHostAndContainer ¶
func (e *ContainerBuilder) AddFiileOrFolderToLinkBetweenConputerHostAndContainer(computerHostPath, insideContainerPath string) (err error)
AddFiileOrFolderToLinkBetweenConputerHostAndContainer (english):
AddFiileOrFolderToLinkBetweenConputerHostAndContainer (português): Monta um arquivo ou pasta entre o computador e o container.
computerHostPath: Caminho do arquivo ou pasta dentro do 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.AddFiileOrFolderToLinkBetweenConputerHostAndContainer("./test/static", "/static") if err != nil { log.Printf("container.AddFiileOrFolderToLinkBetweenConputerHostAndContainer().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)
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
AddImageBuildOptionsBuildArgs (português): Adiciona uma variável durante a construção (--build-arg)
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
func (*ContainerBuilder) AddPortToChange ¶
func (e *ContainerBuilder) AddPortToChange(imagePort string, newPort string)
AddPortToChange (english):
AddPortToChange (português): Define as portas a serem expostas na rede alterando o valor da porta definida na imagem e o valor exposto na rede
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 AddPortToOpen(); 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.AddFiileOrFolderToLinkBetweenConputerHostAndContainer("./test/static", "/static") if err != nil { log.Printf("container.AddFiileOrFolderToLinkBetweenConputerHostAndContainer().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) AddPortToOpen ¶
func (e *ContainerBuilder) AddPortToOpen(value string)
AddPortToOpen (english):
AddPortToOpen (português): Define as portas a serem 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 AddPortToOpen(); 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.AddPortToOpen("3000") // replace container folder /static to host folder ./test/static err = container.AddFiileOrFolderToLinkBetweenConputerHostAndContainer("./test/static", "/static") if err != nil { log.Printf("container.AddFiileOrFolderToLinkBetweenConputerHostAndContainer().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):
ContainerBuildFromImage (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.AddFiileOrFolderToLinkBetweenConputerHostAndContainer("./test/static", "/static") if err != nil { log.Printf("container.AddFiileOrFolderToLinkBetweenConputerHostAndContainer().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) ContainerInspect ¶
func (e *ContainerBuilder) ContainerInspect() (inspect iotmakerdocker.ContainerInspect, err error)
ContainerInspect (english):
ContainerInspect (português): inspeciona o container
func (*ContainerBuilder) ContainerPause ¶
func (e *ContainerBuilder) ContainerPause() (err error)
ContainerPause (english):
ContainerPause (português): pausa o container
func (*ContainerBuilder) ContainerRemove ¶
func (e *ContainerBuilder) ContainerRemove(removeVolumes bool) (err error)
ContainerRemove (english):
ContainerRemove (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):
ContainerStart (português): inicializar um container recem criado ou pausado
func (*ContainerBuilder) ContainerStop ¶
func (e *ContainerBuilder) ContainerStop() (err error)
ContainerStop (english):
ContainerStop (português): parar o container
func (*ContainerBuilder) FindCurrentIPV4Address ¶
func (e *ContainerBuilder) FindCurrentIPV4Address() (IP string, err error)
FindCurrentIPV4Address (english):
FindCurrentIPV4Address (português): Inspeciona a rede e devolve o IP atual do container
Example ¶
var err error GarbageCollector() // create a container 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 AddPortToOpen("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):
FindTextInsideContainerLog (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):
GetChannelOnContainerInspect (português): Canas disparado a cada ciclo do ticker definido em SetInspectInterval()
func (*ContainerBuilder) GetChannelOnContainerReady ¶
func (e *ContainerBuilder) GetChannelOnContainerReady() (channel *chan bool)
GetChannelOnContainerReady (english):
GetChannelOnContainerReady (português): Canal disparado quando o container está pronto para uso
Nota: Este canal espera o container sinalizar que está pronto, caso SetWaitString() não seja definido, ou espera pelo texto definido em SetWaitString() aparecer na saída padrão
func (*ContainerBuilder) GetContainerID ¶
func (e *ContainerBuilder) GetContainerID() (ID string)
GetContainerID (english):
GetContainerID (português): Retorna o ID do container criado
func (*ContainerBuilder) GetContainerLog ¶
func (e *ContainerBuilder) GetContainerLog() (log []byte, err error)
GetContainerLog (english):
GetContainerLog (português): Retorna a saída padrão atual do container.
func (*ContainerBuilder) GetIPV4Address ¶
func (e *ContainerBuilder) GetIPV4Address() (IP string)
GetIPV4Address (english):
GetIPV4Address (português): Retorna o IP de quando o container foi criado.
Nota: Caso o container seja desconectado ou conectado a uma outra rede após a criação, esta informação pode mudar
func (*ContainerBuilder) GetIdByContainerName ¶
func (e *ContainerBuilder) GetIdByContainerName() (err error)
GetIdByContainerName (english):
GetIdByContainerName (português): Retorna o ID do container definido em SetContainerName()
func (*ContainerBuilder) GetImageID ¶
func (e *ContainerBuilder) GetImageID() (ID string)
GetImageID (english):
GetImageID (português): Retorna o ID da imagem.
func (*ContainerBuilder) GetImageName ¶
func (e *ContainerBuilder) GetImageName() (name string)
GetImageName (english):
GetImageName (português): Retorna o nome da imagem.
func (*ContainerBuilder) GetLastInspect ¶
func (e *ContainerBuilder) GetLastInspect() (inspect iotmakerdocker.ContainerInspect)
GetLastInspect (english):
GetLastInspect (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):
GetLastLogs (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):
GetNetworkGatewayIPV4 (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):
GetNetworkGatewayIPV4ByNetworkName (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):
GetNetworkIPV4 (português):
func (*ContainerBuilder) GetNetworkIPV4ByNetworkName ¶
func (e *ContainerBuilder) GetNetworkIPV4ByNetworkName(networkName string) (IPV4 string, err error)
GetNetworkIPV4ByNetworkName (english):
GetNetworkIPV4ByNetworkName (português):
func (*ContainerBuilder) GetNetworkInterface ¶
func (e *ContainerBuilder) GetNetworkInterface() (network isolatedNetwork.ContainerBuilderNetworkInterface)
GetNetworkInterface (english):
GetNetworkInterface (português):
func (*ContainerBuilder) ImageBuildFromFolder ¶
func (e *ContainerBuilder) ImageBuildFromFolder() (err error)
ImageBuildFromFolder (english):
ImageBuildFromFolder (português): transforma o conteúdo da pasta definida em SetBuildFolderPath() em uma 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 recusiva por "Dockerfile" e "dockerfile"
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.AddPortToOpen("3000") // replace container folder /static to host folder ./test/static err = container.AddFiileOrFolderToLinkBetweenConputerHostAndContainer("./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):
ImageBuildFromServer (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/id_rsa e as configurações de ~/.gitconfig
func (*ContainerBuilder) ImageListExposedPorts ¶
func (e *ContainerBuilder) ImageListExposedPorts() (portList []nat.Port, err error)
ImageListExposedPorts (english):
ImageListExposedPorts (português): Lista todas as portas definidas na imagem para serem expostas.
Nota: As portas expostas na criação do container pode ser definidas por SetOpenAllContainersPorts(), AddPortToChange() e AddPortToOpen(); 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 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):
ImageListExposedVolumes (português):
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):
ImagePull (português): baixa a imagem a ser montada. (equivale ao comando docker pull)
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 AddPortToOpen("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):
ImageRemove (português): remove a imagem se não houver containers usando a imagem (remova todos os containers antes do uso, mesmo os parados)
func (*ContainerBuilder) ImageRemoveByName ¶
func (e *ContainerBuilder) ImageRemoveByName(name string) (err error)
ImageRemoveByName (english):
ImageRemoveByName (português): Remove uma imagem se não houver containers usando a imagem
name: nome completo da imagem Nota: pare e remova todos os containers usando a imagem antes de usar este comando
func (*ContainerBuilder) Init ¶
func (e *ContainerBuilder) Init() (err error)
Init (english):
Init (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):
MakeDefaultDockerfileForMe (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 irá expor o volume contendo o arquivo dentro do container.
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
func (*ContainerBuilder) Prayer ¶
func (e *ContainerBuilder) Prayer()
Prayer (english): Programmer prayer
Prayer (português): Oração do programador
func (*ContainerBuilder) RemoveAllByNameContains ¶
func (e *ContainerBuilder) RemoveAllByNameContains(value string) (err error)
RemoveAllByNameContains (english):
RemoveAllByNameContains (português): procuta por redes, volumes, container e imagens que contenham o termo definido em "value" no nome e tenta remover os mesmos
func (*ContainerBuilder) SetBuildFolderPath ¶
func (e *ContainerBuilder) SetBuildFolderPath(value string)
SetBuildFolderPath (english):
SetBuildFolderPath (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 recusiva por "Dockerfile" e "dockerfile"
func (*ContainerBuilder) SetContainerAttachStandardStreamsToTty ¶
func (e *ContainerBuilder) SetContainerAttachStandardStreamsToTty(value bool)
SetContainerAttachStandardStreamsToTty (english):
SetContainerAttachStandardStreamsToTty (português):
func (*ContainerBuilder) SetContainerCommandToRunWhenStartingTheContainer ¶
func (e *ContainerBuilder) SetContainerCommandToRunWhenStartingTheContainer(values []string)
SetContainerCommandToRunWhenStartingTheContainer (english): command to run when stating the container
SetContainerCommandToRunWhenStartingTheContainer (português): comando a ser executado quando o container inicia
func (*ContainerBuilder) SetContainerEntrypointToRunWhenStartingTheContainer ¶
func (e *ContainerBuilder) SetContainerEntrypointToRunWhenStartingTheContainer(values []string)
SetContainerEntrypointToRunWhenStartingTheContainer (english): entrypoint to run when stating the container
SetContainerEntrypointToRunWhenStartingTheContainer (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).
SetContainerHealthcheck (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):
SetContainerName (português): Define o nome do container
value: nome do container
func (*ContainerBuilder) SetContainerRestartPolicyAlways ¶
func (e *ContainerBuilder) SetContainerRestartPolicyAlways()
SetContainerRestartPolicyAlways (english):
SetContainerRestartPolicyAlways (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):
SetContainerRestartPolicyNo (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):
SetContainerRestartPolicyOnFailure (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):
SetContainerRestartPolicyUnlessStopped (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
SetContainerShellForShellFormOfRunCmdEntrypoint (português): define o terminal (shell) para executar o entrypoint
func (*ContainerBuilder) SetEnvironmentVar ¶
func (e *ContainerBuilder) SetEnvironmentVar(value []string)
SetEnvironmentVar (english):
SetEnvironmentVar (português): Define as variáveis de ambiente
value: array de string contendo um variável de ambiente por chave
func (*ContainerBuilder) SetGitCloneToBuild ¶
func (e *ContainerBuilder) SetGitCloneToBuild(url string)
SetGitCloneToBuild (english):
SetGitCloneToBuild (português): Define o caminho de um repositório público para ser usado como base da imagem a ser montada.
url: Endereço do repositório contendo o projeto Nota: * 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.*' Nota: O repositório pode ser definido pelos métodos SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(), SetGitCloneToBuildWithPrivateToken() e SetGitCloneToBuildWithUserPassworh() SetPrivateRepositoryAutoConfig() copia as credencias do git contidas em ~/.ssh/id_rsa e as configurações de ~/.gitconfig Caso o certificado ssh seja protegido com chave, ela pode ser definida com SetGitSshPassword()
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.AddFiileOrFolderToLinkBetweenConputerHostAndContainer("./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):
SetGitCloneToBuildWithPrivateSSHKey (português): Define o caminho de um repositório privado 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 Nota: * Password é o password usado na criação da chave e não password do repositório; o diretório ~/.ssh só é acessado pelo programa se o mesmo for inicializado com nível de acesso administrador; * 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.*' var err error var usr *user.User var privateSSHKeyPath string var file []byte usr, err = user.Current() if err != nil { panic(err) } privateSSHKeyPath = filepath.Join(usr.HomeDir, ".shh", "id_rsa") var container = ContainerBuilder{} container.SetGitCloneToBuildWithPrivateSSHKey(url, privateSSHKeyPath, password) container.SetGitConfigFile(string(file))
func (*ContainerBuilder) SetGitCloneToBuildWithPrivateToken ¶
func (e *ContainerBuilder) SetGitCloneToBuildWithPrivateToken(url, privateToken string)
SetGitCloneToBuildWithPrivateToken (english):
SetGitCloneToBuildWithPrivateToken (português): Define o caminho de um repositório privado para ser usado como base da imagem a ser montada.
url: Endereço do repositório contendo o projeto privateToken: Token gerado dentro do portal git Nota: * 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.*'
func (*ContainerBuilder) SetGitCloneToBuildWithUserPassworh ¶
func (e *ContainerBuilder) SetGitCloneToBuildWithUserPassworh(url, user, password string)
SetGitCloneToBuildWithUserPassworh (english):
SetGitCloneToBuildWithUserPassworh (português): Define o caminho de um repositório privado para ser usado como base da imagem a ser montada.
url: Endereço do repositório contendo o projeto user: Usuário de acesso ao git password: Senha de acesso ao git Nota: * 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.*'
func (*ContainerBuilder) SetGitConfigFile ¶
func (e *ContainerBuilder) SetGitConfigFile(value string)
SetGitConfigFile (english):
SetGitConfigFile (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):
Example: github.com/helmutkemper
SetGitPathPrivateRepository (português):
Exemplo: github.com/helmutkemper
Example ¶
var err error GarbageCollector() var container = ContainerBuilder{} container.SetGitPathPrivateRepository("github.com/helmutkemper") // 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 git@github.com:helmutkemper/iotmaker.docker.builder.private.example.git container.SetGitCloneToBuild("git@github.com:helmutkemper/iotmaker.docker.builder.private.example.git") container.MakeDefaultDockerfileForMe() err = container.SetPrivateRepositoryAutoConfig() if err != nil { panic(err) } // 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.AddFiileOrFolderToLinkBetweenConputerHostAndContainer("./test/static", "/static") if err != nil { panic(err) } // inicialize container object err = container.Init() if err != nil { panic(err) } 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 } } } }(container.GetChannelEvent()) // 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 // 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) SetGitSshPassword ¶
func (e *ContainerBuilder) SetGitSshPassword(password string)
SetGitSshPassword (english):
SetGitSshPassword (português): Define a senha da chave ssh para repositórios git privados.
Nota: O repositório pode ser definido pelos métodos SetGitCloneToBuild(), SetGitCloneToBuildWithPrivateSshKey(), SetGitCloneToBuildWithPrivateToken() e SetGitCloneToBuildWithUserPassworh() SetPrivateRepositoryAutoConfig() copia as credencias do git contidas em ~/.ssh/id_rsa e as configurações de ~/.gitconfig Caso o certificado ssh seja protegido com chave, ela pode ser definida com SetGitSshPassword()
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.
SetImageBuildOptionsCPUPeriod (português):
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.
SetImageBuildOptionsCPUQuota (português):
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).
SetImageBuildOptionsCPUSetCPUs (português):
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.
SetImageBuildOptionsCPUSetMems (português): Define os nós de memória (MEMs) (--cpuset-mems)
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.
SetImageBuildOptionsCPUShares (português):
func (*ContainerBuilder) SetImageBuildOptionsCacheFrom ¶
func (e *ContainerBuilder) SetImageBuildOptionsCacheFrom(values []string)
SetImageBuildOptionsCacheFrom (english): CacheFrom specifies images that are used for matching cache. Images specified here do not need to have a valid parent chain to match cache.
SetImageBuildOptionsCacheFrom (português):
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
SetImageBuildOptionsExtraHosts (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 An entry with the ip address and hostname is created in /etc/hosts inside containers for this build, e.g: 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
SetImageBuildOptionsIsolationDefault (português):
func (*ContainerBuilder) SetImageBuildOptionsIsolationHyperV ¶
func (e *ContainerBuilder) SetImageBuildOptionsIsolationHyperV()
SetImageBuildOptionsIsolationHyperV (english): Set HyperV isolation mode
SetImageBuildOptionsIsolationHyperV (português):
func (*ContainerBuilder) SetImageBuildOptionsIsolationProcess ¶
func (e *ContainerBuilder) SetImageBuildOptionsIsolationProcess()
SetImageBuildOptionsIsolationProcess (english): Set process isolation mode
SetImageBuildOptionsIsolationProcess (português):
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
SetImageBuildOptionsMemory (português):
Use value * KKiloByte, value * KMegaByte and 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 swar (--memory-swap)
Use value * KKiloByte, value * KMegaByte and value * KGigaByte See https://docs.docker.com/engine/reference/run/#user-memory-constraints
SetImageBuildOptionsMemorySwap (português):
Use value * KKiloByte, value * KMegaByte and value * KGigaByte See https://docs.docker.com/engine/reference/run/#user-memory-constraints
func (*ContainerBuilder) SetImageBuildOptionsNoCache ¶
func (e *ContainerBuilder) SetImageBuildOptionsNoCache(value bool)
SetImageBuildOptionsNoCache (english): Set image build no cache
SetImageBuildOptionsNoCache (português):
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
SetImageBuildOptionsPlatform (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
SetImageBuildOptionsSecurityOpt (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
SetImageBuildOptionsSquash (português):
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/
SetImageBuildOptionsTarget (português): Constrói 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):
SetImageName (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):
SetInspectInterval (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):
SetNetworkDocker (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.AddPortToOpen("27017") // se a environment var list mongoDocker.SetEnvironmentVar( []string{ "--host 0.0.0.0", }, ) // set a MongoDB data dir to ./test/data err = mongoDocker.AddFiileOrFolderToLinkBetweenConputerHostAndContainer("./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):
SetOpenAllContainersPorts (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 AddPortToOpen(); Por padrão, todas as portas ficam fechadas; A função ImageListExposedPorts() retorna todas as portas definidas na imagem para serem expostas.
func (*ContainerBuilder) SetPrivateRepositoryAutoConfig ¶
func (e *ContainerBuilder) SetPrivateRepositoryAutoConfig() (err error)
SetPrivateRepositoryAutoConfig (english):
SetPrivateRepositoryAutoConfig (português): Copia a chave ssh ~/.ssh/id_rsa e o arquivo ~/.gitconfig para as variáveis SSH_ID_RSA_FILE e GITCONFIG_FILE.
Dentro do Dockerfile
func (*ContainerBuilder) SetSshIdRsaFile ¶
func (e *ContainerBuilder) SetSshIdRsaFile(value string)
SetSshIdRsaFile (english):
SetSshIdRsaFile (português):
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):
SetSshKnownHostsFile (português):
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):
SetWaitString (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
func (*ContainerBuilder) SetWaitStringWithTimeout ¶
func (e *ContainerBuilder) SetWaitStringWithTimeout(value string, timeout time.Duration)
SetWaitStringWithTimeout (english):
SetWaitStringWithTimeout (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):
WaitForTextInContainerLog (português): Para a execução do objeto até o texto ser encontrado na saída padrão do container
value: texto indicativo de evento apresentado na saída padrão do container
func (*ContainerBuilder) WaitForTextInContainerLogWithTimeout ¶
func (e *ContainerBuilder) WaitForTextInContainerLogWithTimeout(value string, timeout time.Duration) (dockerLogs string, err error)
WaitForTextInContainerLogWithTimeout (english):
WaitForTextInContainerLogWithTimeout (português):
type DockerfileAuto ¶
type DockerfileAuto interface {
MountDefaultDockerfile(args map[string]*string, changePorts []dockerfileGolang.ChangePort, openPorts []string, volumes []mount.Mount) (dockerfile string, err error)
}
DockerfileAuto (english):
DockerfileAuto (português):
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.
HealthConfig (português):
type Overloading ¶
type Overloading struct {
// contains filtered or unexported fields
}
func (*Overloading) Init ¶
func (e *Overloading) Init(listenPort string, invert bool) (err error)
Example ¶
var err error GarbageCollector() var mongoDocker = &ContainerBuilder{} mongoDocker.SetImageName("mongo:latest") mongoDocker.SetContainerName("container_delete_mongo_after_test") //mongoDocker.AddPortToChange("27017", "27016") mongoDocker.AddPortToOpen("27017") mongoDocker.SetEnvironmentVar( []string{ "--host 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) } return 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 serverContainer = &ContainerBuilder{} // add container to network serverContainer.SetNetworkDocker(&netDocker) // new image name delete:latest serverContainer.SetImageName("delete:latest") // container name container_delete_server_after_test serverContainer.SetContainerName("container_delete_server_after_test") // git project to clone https://github.com/helmutkemper/iotmaker.docker.util.whaleAquarium.sample.git serverContainer.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] serverContainer.SetWaitStringWithTimeout("Stating server on port 3000", 10*time.Second) // change and open port 3000 to 3030 //serverContainer.SetDoNotOpenContainersPorts() //serverContainer.AddPortToChange("3000", "3030") serverContainer.AddPortToOpen("3000") // replace container folder /static to host folder ./test/static err = serverContainer.AddFiileOrFolderToLinkBetweenConputerHostAndContainer("./test/static", "/static") if err != nil { log.Printf("container.AddFiileOrFolderToLinkBetweenConputerHostAndContainer().error: %v", err.Error()) util.TraceToLog() panic(err) } // inicialize container object err = serverContainer.Init() if err != nil { util.TraceToLog() panic(err) } // builder new image from git project err = serverContainer.ImageBuildFromServer() if err != nil { util.TraceToLog() log.Printf("container.ImageBuildFromServer().error: %v", err.Error()) panic(err) } // container build from image delete:latest err = serverContainer.ContainerBuildFromImage() if err != nil { util.TraceToLog() log.Printf("container.ContainerBuildFromImage().error: %v", err.Error()) panic(err) } log.Printf("ip address: %v", serverContainer.GetIPV4Address()) return var overload = Overloading{} overload.SetNetworkDocker(&netDocker) overload.SetBuilderToOverload(serverContainer) err = overload.Init("3000", false) if err != nil { util.TraceToLog() log.Printf("error: %v", err.Error()) panic(err) }
Output:
func (*Overloading) SetBuilderToOverload ¶
func (e *Overloading) SetBuilderToOverload(value *ContainerBuilder)
fixme: interface
func (*Overloading) SetNetworkDocker ¶
func (e *Overloading) SetNetworkDocker(network isolatedNetwork.ContainerBuilderNetworkInterface)
SetNetworkDocker (english):
SetNetworkDocker (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{}
Source Files ¶
- conts.go
- doc.go
- funcAddFiileOrFolderToLinkBetweenConputerHostAndContainer.go
- funcAddImageBuildOptionsBuildArgs.go
- funcAddImageBuildOptionsGitCredentials.go
- funcAddPortToChange.go
- funcAddPortToOpen.go
- funcContainerBuildFromImage.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
- funcImageListExposedPorts.go
- funcImageListExposedVolumes.go
- funcImagePull.go
- funcImageRemove.go
- funcImageRemoveByName.go
- funcIncIpV4Address.go
- funcInit.go
- funcMakeDefaultGolangDockerfileForMe.go
- funcPrayer.go
- funcRemoveAllByNameContains.go
- funcSetBuildFolderPath.go
- funcSetContainerAttachStandardStreamsToTty.go
- funcSetContainerCommandToRunWhenStartingTheContainer.go
- funcSetContainerEntrypointToRunWhenStartingTheContainer.go
- funcSetContainerHealthcheck.go
- funcSetContainerName.go
- funcSetContainerRestartPolicyAlways.go
- funcSetContainerRestartPolicyNo.go
- funcSetContainerRestartPolicyOnFailure.go
- funcSetContainerRestartPolicyUnlessStopped.go
- funcSetContainerShellForShellFormOfRunCmdEntrypoint.go
- funcSetDoNotOpenContainersPorts.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
- funcSetPrivateRepositoryAutoConfig.go
- funcSetSshIdRsaFile.go
- funcSetSshKnownHostsFile.go
- funcSetWaitString.go
- funcSetWaitStringWithTimeout.go
- funcVerifyImageName.go
- funcWaitForTextInContainerLog.go
- funcWaitForTextInContainerLogWithTimeout.go
- typeContainerBuilder.go
- typeDockerfileAuto.go
- typeGitData.go
- typeHealthConfig.go
- typeOverloading.go