Docker plus Emscripten

I have started to experiment with Docker. I thought that I'd try it out, because I wanted to use Emscripten to compile some C programs to JavaScript (which uses the asm.js style). Since getting Emscripten set up can take some time, I thought that a pre-configured Docker container might be a useful shortcut. I also wanted to try out Docker on my MacBook at some stage, so that I can do Linuxy things without having to fire up a full Virtual Machine.

But for now, I am doing this on Ubuntu Server 15.04. Setting up Docker was pretty painless, like this:

sudo apt-get install

...after which I did a reboot to make sure the docker daemon started automatically at boot-time. I then verified everything was OK by doing this:

sudo docker run hello-world

To make it better, you can set up a docker group so that docker does not need to run with sudo. I did that like this:

sudo usermod -aG docker [my_username_here]

After logging out and back in, Docker does not need to be run with sudo. Cool... now to try Emscripten inside docker. I found a container called apiaryio/base-emscripten-dev which looked like it should do the hard work for me. I tried it out like this:

docker run apiaryio/base-emscripten-dev emcc -v

Which will test things out. The first time takes a while and downloads hundreds of megabytes as it pulls down the repository. But eventually a message comes back from the Emscripten compiler. I thought that it would be really cool to be able to call the Emscripten compiler, emcc inside Docker from the host machine. So I came up with this script:

docker run -v ${PWD}:/src apiaryio/base-emscripten-dev \
/bin/sh -c "cd /src; emcc $*"

...which I copied into /usr/local/bin named as demcc and marked it executable (sudo chmod +x /usr/local/bin/demcc). This script does a few things:

  1. mounts the current directory on the host in the Docker container (as /src)
  2. in the docker container, changes to the correct directory
  3. passes any parameters on to emcc in the container

So now I can just do this:

demcc hello.c -o hello.html

Which will compile the local C file into JavaScript, with all the hard work done inside a Docker container. So now Emscripten is working, and I didn't have to set it up. Happy days! I guess this same approach would work with other types of compilation, like cross-compiling for other platforms. I need to try that.