How to show X11 windows with Docker on Mac
I never would have thought that I would need this feature. Up until now, I only used Docker to get some non-UI environments running, like a local PostgreSQL database or an Android build environment for GitLab CI.
Right now I am part of a team called ‘Happy Robots’ that works on the final project of Udacity’s Self-Driving Car Engineer Nanodegree. That is: Writing and running code on an actual self-driving car!
For running the code the 3 Mac users in our 5-person team are using a Docker image running the ROS, which is only available for Linux. You might wonder why we would need a UI for running the algorithms, and you are right: We don’t. But we included a dashboard built on the library pygame, which we use to render the track, current waypoints, position of the vehicle, traffic lights and their status and much more later on. This is quite helpful to visualize whether our algorithms behave correctly. Here a snapshot of simulator and the pygame dashboard, running on a native Ubuntu installation of my team mate Simon Ritzel:
To get the pygame running on my Mac, I had to do a few things:
- Install the latest XQuartz X11 server and run it
- Activate the option ‘Allow connections from network clients’ in XQuartz settings
- Quit & restart XQuartz (to activate the setting)
Then I tried out to run a Firefox instance and forward it via X11. The recipe:
And wow, it’s actually running — a Linux Firefox on my Mac! Notice the trick using host.docker.internal as display name. That’s a hostname that points to the host machine, so we don’t have to deal with changing IP addresses.
To get our pygame dashboard running, I just had to do three things:
- Ensure localhost is allowed X11 forwarding:
xhost + 127.0.0.1
- Inside the docker image, install pygame and set the display variable:
pip install pygame
- Run our algorithm!
Now, let’s have a look at the result:
Awesome! This should allow you to run a lot of Linux UI applications on your Mac. Of course some things don’t work and the performance could be improved, too. But it gives you a great starting point! 😊