Execute code in many languages with Docker!
Docker Exec is a collection of Docker images capable of executing code in many different programming languages without requiring a single compiler or script interpreter on your machine.
The dexec
command line interface provides a simple front end, picking the appropriate Docker image based on the source extension.
See the dexec installation guide to get started
Let's take a closer look at one of the examples, helloworld.cpp:
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
executing it is simple:
$ dexec foo.cpp
Hello, World!
Docker Exec also supports passing arguments to the executing program, passing arguments to the compiler, mounting extra files and directories in the executing container as well as the ability to make source files executable as scripts using a shebang.
Docker Exec allows you to run code in a compiled language just as easily as you can for interpreted languages. This is useful for speeding up your ability to try things out in compiled languages.
The uniform interface used to execute source for all of the different languages means that calls to dexec
can be shelled out from other programs who need to execute arbitrary source, for example automated answer checkers for code tests in pre-interview situations or for university exercises.
Another benefit is that the only dependency on your machine becomes Docker instead of lots of different compilers and interpreters. Docker is a powerful tool and a lot is said about its potential for running web services and databases. However, it's also great for single program execution too and this is an example of how tools can be usefully virtualised just as well as web services.
Further to this, the virtualisation of the compilation and execution acts as a sandbox in the event you're not entirely sure how safe a piece of code is to run.
A Docker image exists for each target language, with an associated automated build job on Docker Hub. The image contains the compiler, runtime or interpreter for that language and a bash script that does any of the following depending on the language:
The dexec
utility wraps the following command:
$ docker run -t --rm \
-v $(pwd -P)/foo.cpp:/tmp/dexec/build/foo.cpp \
dexec/lang-cpp foo.cpp
Arguments can be passed to the executing code using:
-a bar
--arg bar
--arg=bar
Arguments can be passed to the compiler (if the language has one) using:
-b foo
--build-arg foo
--build-arg=foo
Extra file and folders can be mounted in the container with dexec
using:
-i foo.hpp
--include foo.hpp
--include=foo.hpp
Prefixing a source file with a shebang that invokes dexec will make it executable:
#!/usr/bin/env dexec
The following languages are available:
I'm Andy Stanton (@andystanton).
Documentation can be found and issues raised in each image's repository.