Execute go run execute.go python test.py
Last active
October 29, 2018 23:33
-
-
Save vdparikh/48d9e3e5828d1bc8966aedfc36a51647 to your computer and use it in GitHub Desktop.
Execute scripts from /scripts folder inside a container
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"log" | |
"os" | |
"github.com/ahmetalpbalkan/dexec" | |
"github.com/fsouza/go-dockerclient" | |
) | |
func main() { | |
endpoint := "unix:///var/run/docker.sock" | |
dockerClient, err := docker.NewClient(endpoint) | |
if err != nil { | |
panic(err) | |
} | |
d := dexec.Docker{dockerClient} | |
pwd, _ := os.Getwd() | |
image := "" | |
baseCmd := []string{} | |
switch os.Args[1] { | |
case "python": | |
image = "python:alpine" | |
baseCmd = []string{"python"} | |
case "go": | |
image = "golang:alpine" | |
baseCmd = []string{"go", "run"} | |
case "node": | |
image = "node:alpine" | |
baseCmd = []string{"node"} | |
default: | |
image = "busybox" | |
baseCmd = []string{"/bin/sh", "-c"} | |
} | |
m, _ := dexec.ByCreatingContainer( | |
docker.CreateContainerOptions{ | |
Config: &docker.Config{ | |
Image: image, | |
Volumes: map[string]struct{}{ | |
"/scripts": struct{}{}, | |
}, | |
}, | |
HostConfig: &docker.HostConfig{ | |
Binds: []string{ | |
fmt.Sprintf("%s:%s", pwd+"/scripts", "/scripts"), | |
}, | |
}, | |
}, | |
) | |
baseCmd = append(baseCmd, "/scripts/"+os.Args[2]) | |
fmt.Println("Running", image, baseCmd) | |
cmd := d.Command(m, baseCmd[0], baseCmd[1:]...) | |
b, err := cmd.Output() | |
if err != nil { | |
log.Fatal(err) | |
} | |
log.Printf("%s", b) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment