DIRA is a Golang package that simplifies the execution of commands in Docker containers via Docker Remote Access.
Install DIRA using the following command:
go get github.com/mindwingx/dira
Please ensure that you have enabled Docker Remote Access on your machine.
Note: Enabling it with 0.0.0.0:<port>
is not recommended.
Executing commands in Docker containers is fast and straightforward with DIRA. Here's an example of how to use it:
const (
hostURLOrIP = "http://127.0.0.1:2375"
containerName = "ubuntu"
cmd = "echo Hello World"
)
// Create a DIRA instance with the desired configuration.
dockerCmd := dira.SetOpts(hostURLOrIP, containerName, cmd)
// Execute the command in the Docker container.
result, err := dockerCmd.Exec()
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Command Output: %s\n", result)
Imagine needing to perform operations like file encryption, media compression, or OS layer executions within a Microservice process, but not directly executable. These tasks might run on a VPS's localhost or a remote server.
Handling container interactions and complex commands can complicate the process. DIRA simplifies this by enabling communication between containers through Docker's REST API. While other solutions exist, DIRA offers a developer-friendly approach, especially in remote access scenarios.
The following examples are based on a simple Dockerfile
that uses only the FROM ubuntu:latest
instruction. We've built the corresponding image using the command docker build -t ubuntu .
, and it's now running as a container named ubuntu
with the command docker run --name untu -ti -d ubuntu
.
- If you find that the related process is taking longer, you can increase the timeout by specifying the duration in seconds.
dockerCmd := dira.SetOpts(hostURLOrIP, containerName, cmd)
// Execute the command in the Docker container.
result, err := dockerCmd.
SetTimeout(20).
Exec()
- If the execution contains responses with special characters like
\n
,EOF
, and others, utilize theRemoveMatching()
method to eliminate them fromStdout
.
dockerCmd := dira.SetOpts(hostURLOrIP, containerName, cmd)
result, err := dockerCmd.
RemoveMatching().
Exec()
- If you have multiple commands to execute on a specific container, create an instance object and execute them sequentially.
dockerCmd := dira.SetOpts(hostURLOrIP, containerName, "")
result1, err1 := dockerCmd.
SetContainer("new-container-name"). // modify the container of the same network to run the command
SetCommand("echo Command 1").
Exec()
result2, err2 := dockerCmd.
SetCommand("echo Command 2").
SetTimeout(20).
Exec()
result3, err3 := dockerCmd.
SetCommand("echo Command 3").
RemoveMatching().
Exec()
Contributions are welcome! If you find any issues or have suggestions for improvement, please submit an issue or a pull request on the GitHub repository.
The DIRA package is open-source software licensed under the MIT license.
The DIRA package is developed and maintained by Milad Roudgarian.