Once you understand how a native workstation environment works—as covered in how to install ROS 2 Jazzy on Ubuntu 24.04 and automate your .bashrc environment—the next challenge is eliminating environment drift across machines. Robotics software stacks are tightly coupled to specific Ubuntu releases, C++ ABI versions, OpenCV builds, and Gazebo plugins. When one developer runs Ubuntu 22.04 and another runs Ubuntu 24.04 with slightly different apt package versions, identical source code can fail to compile or exhibit subtle runtime mismatches. Packaging the development workspace inside a Docker container pins the entire OS and ROS 2 dependency tree to a single image definition.
This tutorial explains how to choose the right ROS 2 Jazzy base image, build a Dockerfile that prevents root file-ownership conflicts, expose host networking and X11 GUI windows (rviz2), connect multiple terminals to a single container using docker exec, and integrate VS Code through both Attach to Running Container and .devcontainer/devcontainer.json.
Why Containerize ROS 2 Jazzy: Host Comparison and Base Image Selection
When a native ROS 2 installation becomes corrupted by conflicting package upgrades or custom library builds, cleaning /opt/ros and /usr/local often requires hours of manual repair. With Docker, removing and recreating the container restores a clean environment in seconds. Isolating system dependencies also prevents conflicts when working alongside GPU machine learning stacks, a common issue explored in the MuJoCo, LeRobot, and CUDA installation error troubleshooting guide.
| Dimension | Native Host Installation | Docker Container Environment |
|---|---|---|
| Team Consistency | Varies with each machine’s apt history | Locked identically via Dockerfile and image digest |
| System Cleanliness | Modifies /opt/ros, /etc/apt, and system Python | Completely isolated; reset instantly with docker rm |
| Multi-Distro Support | Mixing Humble and Jazzy risks PATH collisions | Run Humble and Jazzy side by side in separate containers |
| Onboarding Speed | Manual multi-step setup guide per workstation | Single docker compose up -d or Reopen in Container |
The official ROS images on Docker Hub and the OSRF repository provide four primary image variants for ROS 2 Jazzy:
| Image Tag | Included Packages | Target Use Case |
|---|---|---|
ros:jazzy-ros-core | Minimal runtime and core communication libraries | Lightweight embedded deployment and CI |
ros:jazzy (ros-base) | rclcpp, rclpy, CLI tools, colcon, core messages | Headless robot computers (SBCs) and backend nodes |
osrf/ros:jazzy-desktop | ros-base + rviz2, rqt, tutorial demos, GUI tools | Standard developer workstation (used in this guide) |
ros:jazzy-perception | ros-base + OpenCV, PCL, image transport pipelines | Computer vision and point-cloud processing containers |
Because the base ros:jazzy tag omits rviz2 and graphical debugging tools, it cannot render robot models visually. Starting with the URDF XML syntax and link/joint tree guide, visual inspection in RViz2 is required at every step, making osrf/ros:jazzy-desktop the recommended base image for development.
Designing the Dockerfile and Container Launch Flags
Running colcon build or creating files as the default root user inside a container causes files inside the bind-mounted ~/ros2_ws host directory to become owned by root:root, blocking edits from the host OS. To prevent permission conflicts, define a non-root user (ros) inside the Dockerfile whose UID and GID match the host user (typically 1000).
FROM osrf/ros:jazzy-desktop
ARG USERNAME=ros
ARG USER_UID=1000
ARG USER_GID=1000
RUN apt-get update && apt-get install -y --no-install-recommends \
locales sudo git curl tmux nano \
ros-jazzy-urdf-tutorial \
ros-jazzy-joint-state-publisher-gui \
ros-jazzy-xacro \
ros-jazzy-ros-gz \
python3-colcon-common-extensions \
&& rm -rf /var/lib/apt/lists/*
RUN locale-gen en_US en_US.UTF-8 \
&& update-locale LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8
ENV LANG=en_US.UTF-8
# Remove default UID 1000 user if present in the Ubuntu 24.04 base layer, then create 'ros'
RUN if id -u ${USER_UID} >/dev/null 2>&1; then userdel -r $(id -un ${USER_UID}); fi \
&& groupadd --gid ${USER_GID} ${USERNAME} \
&& useradd --uid ${USER_UID} --gid ${USER_GID} -m -s /bin/bash ${USERNAME} \
&& echo "${USERNAME} ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/${USERNAME} \
&& chmod 0440 /etc/sudoers.d/${USERNAME}
USER ${USERNAME}
RUN echo "source /opt/ros/jazzy/setup.bash" >> ~/.bashrc \
&& echo "if [ -f /ros2_ws/install/setup.bash ]; then source /ros2_ws/install/setup.bash; fi" >> ~/.bashrc \
&& echo "export ROS_DOMAIN_ID=11" >> ~/.bashrc
WORKDIR /ros2_ws
Build the image, grant local Docker containers access to the host X11 server, and launch the container in detached interactive mode (-itd):
docker build -t ros2-jazzy-dev:1.0 .
# Allow local container processes to open X11 GUI windows on the host display
xhost +local:docker
docker run -itd --name ros2_jazzy \
--net=host --ipc=host \
-e DISPLAY=${DISPLAY} \
-v /tmp/.X11-unix:/tmp/.X11-unix:rw \
-v ~/ros2_ws:/ros2_ws \
ros2-jazzy-dev:1.0 bash
Each flag addresses a specific robotics requirement:
| Flag | Purpose in ROS 2 Development |
|---|---|
--name ros2_jazzy | Assigns a fixed container name so subsequent shells can attach without looking up container IDs |
--net=host | Shares the host network stack directly so DDS UDP multicast discovery works without bridge NAT issues |
--ipc=host | Shares host inter-process memory, enabling Fast DDS shared-memory zero-copy transport for high-rate topics |
-e DISPLAY + /tmp/.X11-unix | Forwards the host X11 display socket into the container so rviz2 and rqt open natively on screen |
-v ~/ros2_ws:/ros2_ws | Bind-mounts the host workspace folder into the container so source code persists across container rebuilds |
--device=/dev/ttyUSB0 | Passes physical USB serial sensors (LiDAR, ESP32, IMU) into the container (add only when physically plugged in) |
As explained in the official ROS 2 environment configuration documentation, DDS nodes discover each other within a ROS_DOMAIN_ID via multicast packets. Under default Docker bridge networking, multicast traffic is often isolated from the host; --net=host on Linux removes that barrier completely.
Multi-Terminal Container Access: docker exec vs docker attach and the 3-Terminal Pattern
Developing with ROS 2 requires running multiple concurrent processes: one terminal for launching robot state publishers or hardware drivers, a second terminal for inspecting topic rates and TF trees, and a third terminal for rviz2 or colcon build. Choosing the wrong Docker command when opening additional terminals is one of the most frequent sources of confusion.
| Command Pattern | Example Invocation | Internal Container Behavior | Safety and Recommendation |
|---|---|---|---|
docker exec | docker exec -it ros2_jazzy bash | Spawns a brand-new independent shell process inside the existing container | Recommended: Closing the terminal or pressing Ctrl+C leaves the container running |
docker attach | docker attach ros2_jazzy | Attaches standard input/output directly to the container’s PID 1 main process | Dangerous: Pressing Ctrl+C or typing exit can shut down the entire container |
docker run | docker run -it ros2-jazzy-dev:1.0 | Creates a completely separate new container instance from the image | Avoid: Splits file systems and process trees across duplicate containers |
As detailed in the official Docker docker container exec reference, docker exec creates a new process inside the target container’s existing Linux namespaces. Even if you open ten terminal tabs via docker exec -it ros2_jazzy bash, only a single container is running, and every tab shares the exact same /ros2_ws filesystem, ROS_DOMAIN_ID, and ROS 2 node graph.
The Standard 3-Terminal Robotics Workflow
Open three terminal tabs on the host and connect all three to the running ros2_jazzy container using docker exec:
# [Terminal 1] Core robot bringup and launch files
docker exec -it -u ros -w /ros2_ws ros2_jazzy bash
ros2 launch urdf_tutorial display.launch.py model:=/opt/ros/jazzy/share/urdf_tutorial/urdf/01-myfirst.urdf
# [Terminal 2] Topic inspection, frequency checks, and TF diagnostics
docker exec -it -u ros -w /ros2_ws ros2_jazzy bash
ros2 node list
ros2 topic list
ros2 topic echo /joint_states --once
# [Terminal 3] Workspace compilation (colcon) and package management
docker exec -it -u ros -w /ros2_ws ros2_jazzy bash
colcon build --symlink-install && source install/setup.bash
To manage the container lifecycle across reboots without losing internal state, use docker stop and docker start rather than docker rm:
docker ps -a
docker stop ros2_jazzy # Pause work cleanly without deleting the container
docker start ros2_jazzy # Resume the existing container
docker exec -it -u ros ros2_jazzy bash
If you prefer not to type long docker run arguments, store the configuration in a compose.yaml file so team members can start the environment with docker compose up -d and open shells with docker compose exec ros2 bash:
services:
ros2:
build: .
image: ros2-jazzy-dev:1.0
container_name: ros2_jazzy
network_mode: host
ipc: host
user: "1000:1000"
working_dir: /ros2_ws
environment:
- DISPLAY=${DISPLAY}
- ROS_DOMAIN_ID=11
volumes:
- ~/ros2_ws:/ros2_ws
- /tmp/.X11-unix:/tmp/.X11-unix:rw
stdin_open: true
tty: true
command: bash
Connecting VS Code to the Container: Attach (Method A) vs .devcontainer (Method B)
Editing multi-link URDF XML files or Python nodes over raw terminal editors makes catching tag mismatches difficult. According to the official VS Code Dev Containers documentation, VS Code can run its backend server directly inside the container, providing full IntelliSense, XML schema validation, and integrated terminal tabs while keeping the UI on the host.
| Feature | Method A: Attach to Running Container | Method B: .devcontainer/devcontainer.json |
|---|---|---|
| How It Connects | Attaches directly to an already-running ros2_jazzy container | Builds/starts the container automatically via Reopen in Container |
| Config File Required | None (uses the container started by docker run or compose) | Requires .devcontainer/devcontainer.json in the workspace |
| Extension Provisioning | Installed manually once inside the attached container session | Declared in the extensions array and installed automatically |
| Best Suited For | Quick lab sessions and existing long-running containers | Team repositories requiring version-controlled IDE environments |
1. Method A: Attach to an Already Running Container
When ros2_jazzy is already running in the background, follow these five steps to connect VS Code immediately:
- Install the Dev Containers (
ms-vscode-remote.remote-containers) and Docker extensions on the host VS Code instance. - Open the Command Palette (
Ctrl+Shift+P) or click the Docker sidebar icon. - Run
Dev Containers: Attach to Running Container...and select/ros2_jazzyfrom the list. - Once the new VS Code window opens (showing
Container ros2_jazzyin the bottom-left corner), selectFile -> Open Folderand open/ros2_ws. - Open the integrated terminal (
Ctrl+`) and runwhoami,printenv ROS_DISTRO, andros2 topic listto confirm you are operating inside the container as userros.
2. Method B: Codify the Environment with .devcontainer/devcontainer.json
To automate container creation, volume mounting, and extension installation for every contributor cloning the repository, create .devcontainer/devcontainer.json:
{
"name": "ROS 2 Jazzy Dev",
"build": {
"dockerfile": "../Dockerfile",
"context": ".."
},
"runArgs": [
"--net=host",
"--ipc=host"
],
"mounts": [
"source=/tmp/.X11-unix,target=/tmp/.X11-unix,type=bind",
"source=${localWorkspaceFolder},target=/ros2_ws,type=bind"
],
"containerEnv": {
"DISPLAY": "${localEnv:DISPLAY}",
"ROS_DOMAIN_ID": "11"
},
"workspaceFolder": "/ros2_ws",
"remoteUser": "ros",
"postCreateCommand": "bash -lc 'source /opt/ros/jazzy/setup.bash && rosdep update'",
"customizations": {
"vscode": {
"settings": {
"python.defaultInterpreterPath": "/usr/bin/python3",
"ros.distro": "jazzy"
},
"extensions": [
"ms-iot.vscode-ros",
"ms-python.python",
"ms-vscode.cpptools",
"ms-vscode.cmake-tools",
"redhat.vscode-xml"
]
}
}
}
Recommended VS Code Extensions Inside the Container
Because VS Code separates UI extensions on the host from language extensions inside the remote container, verify in the Extensions panel (Ctrl+Shift+X) that the following extensions are installed under the DEV CONTAINER section:
- ROS (
ms-iot.vscode-ros): Provides ROS 2 package creation commands, launch file debugging, and URDF preview support when"ros.distro": "jazzy"is configured. - Python (
ms-python.python): Indexes/opt/ros/jazzy/lib/python3.12/site-packagesinside the container sorclpyand message imports autocomplete cleanly. - XML (
redhat.vscode-xml): Validates URDF and Xacro tag hierarchies and highlights unclosed XML elements on save. - C/C++ and CMake Tools (
ms-vscode.cpptools,ms-vscode.cmake-tools): Resolves/opt/ros/jazzy/includeheaders and enables step-through debugging forament_cmakenodes.
Using VS Code’s Split Terminal button inside the Dev Container reproduces the 3-terminal docker exec pattern inside a single window: edit URDF or Python files in the main editor pane while running colcon build --symlink-install, ros2 launch, and ros2 topic echo across side-by-side integrated terminal panes.
Troubleshooting Matrix for Docker and VS Code ROS 2 Setups
Use this reference table to resolve the most common container networking, GUI, and permission issues:
| Symptom or Error Message | Root Cause | Resolution |
|---|---|---|
cannot connect to X server when launching rviz2 | Missing host X11 permission or missing /tmp/.X11-unix mount | Run xhost +local:docker on the host and verify echo $DISPLAY inside the container |
| Container nodes invisible to host or other terminals | Container launched with default bridge network or mismatched domain | Recreate container with --net=host --ipc=host and verify identical ROS_DOMAIN_ID |
Cannot save workspace files on host (Permission denied) | Files created inside container as root (UID 0) | Build image with a non-root user matching host UID 1000 and pass -u ros to docker exec |
Error response from daemon: No such container | Container is stopped (Exited) or named differently | Check docker ps -a and resume with docker start ros2_jazzy |
ros2: command not found in VS Code terminal | Shell opened without reading ~/.bashrc or setup line missing | Ensure source /opt/ros/jazzy/setup.bash is in container ~/.bashrc |
| Slow 3D rendering in Gazebo inside container | X11 forwarding falling back to CPU software rendering | Run heavy 3D simulators on the host OS while running ROS 2 nodes in the container over --net=host |