Skip to content

Reproducible ROS 2 Jazzy Environments with Docker: Multi-Terminal docker exec and VS Code Dev Containers

Configure an osrf/ros:jazzy-desktop Docker container with host networking, X11, multi-terminal docker exec workflows, and VS Code Dev Containers integration.

Contents

Key takeaways

  1. Containerizing ROS 2 Jazzy eliminates OS and library drift across developer machines while keeping the host Ubuntu installation clean and easily recoverable.
  2. Because ROS 2 DDS discovery relies on UDP multicast and shared memory, Linux containers should run with –net=host and –ipc=host for transparent host-container communication.
  3. Always open additional terminal sessions with docker exec -it rather than docker run (which spawns isolated containers) or docker attach (which terminates the container on Ctrl+C).
  4. Use VS Code Attach to Running Container for quick interactive sessions or .devcontainer/devcontainer.json to codify mounts, run arguments, and container-side extensions in Git.

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.

DimensionNative Host InstallationDocker Container Environment
Team ConsistencyVaries with each machine’s apt historyLocked identically via Dockerfile and image digest
System CleanlinessModifies /opt/ros, /etc/apt, and system PythonCompletely isolated; reset instantly with docker rm
Multi-Distro SupportMixing Humble and Jazzy risks PATH collisionsRun Humble and Jazzy side by side in separate containers
Onboarding SpeedManual multi-step setup guide per workstationSingle 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 TagIncluded PackagesTarget Use Case
ros:jazzy-ros-coreMinimal runtime and core communication librariesLightweight embedded deployment and CI
ros:jazzy (ros-base)rclcpp, rclpy, CLI tools, colcon, core messagesHeadless robot computers (SBCs) and backend nodes
osrf/ros:jazzy-desktopros-base + rviz2, rqt, tutorial demos, GUI toolsStandard developer workstation (used in this guide)
ros:jazzy-perceptionros-base + OpenCV, PCL, image transport pipelinesComputer 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:

FlagPurpose in ROS 2 Development
--name ros2_jazzyAssigns a fixed container name so subsequent shells can attach without looking up container IDs
--net=hostShares the host network stack directly so DDS UDP multicast discovery works without bridge NAT issues
--ipc=hostShares host inter-process memory, enabling Fast DDS shared-memory zero-copy transport for high-rate topics
-e DISPLAY + /tmp/.X11-unixForwards the host X11 display socket into the container so rviz2 and rqt open natively on screen
-v ~/ros2_ws:/ros2_wsBind-mounts the host workspace folder into the container so source code persists across container rebuilds
--device=/dev/ttyUSB0Passes 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 PatternExample InvocationInternal Container BehaviorSafety and Recommendation
docker execdocker exec -it ros2_jazzy bashSpawns a brand-new independent shell process inside the existing containerRecommended: Closing the terminal or pressing Ctrl+C leaves the container running
docker attachdocker attach ros2_jazzyAttaches standard input/output directly to the container’s PID 1 main processDangerous: Pressing Ctrl+C or typing exit can shut down the entire container
docker rundocker run -it ros2-jazzy-dev:1.0Creates a completely separate new container instance from the imageAvoid: 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.

FeatureMethod A: Attach to Running ContainerMethod B: .devcontainer/devcontainer.json
How It ConnectsAttaches directly to an already-running ros2_jazzy containerBuilds/starts the container automatically via Reopen in Container
Config File RequiredNone (uses the container started by docker run or compose)Requires .devcontainer/devcontainer.json in the workspace
Extension ProvisioningInstalled manually once inside the attached container sessionDeclared in the extensions array and installed automatically
Best Suited ForQuick lab sessions and existing long-running containersTeam 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:

  1. Install the Dev Containers (ms-vscode-remote.remote-containers) and Docker extensions on the host VS Code instance.
  2. Open the Command Palette (Ctrl+Shift+P) or click the Docker sidebar icon.
  3. Run Dev Containers: Attach to Running Container... and select /ros2_jazzy from the list.
  4. Once the new VS Code window opens (showing Container ros2_jazzy in the bottom-left corner), select File -> Open Folder and open /ros2_ws.
  5. Open the integrated terminal (Ctrl+`) and run whoami, printenv ROS_DISTRO, and ros2 topic list to confirm you are operating inside the container as user ros.

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"
      ]
    }
  }
}

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-packages inside the container so rclpy and 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/include headers and enables step-through debugging for ament_cmake nodes.

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 MessageRoot CauseResolution
cannot connect to X server when launching rviz2Missing host X11 permission or missing /tmp/.X11-unix mountRun xhost +local:docker on the host and verify echo $DISPLAY inside the container
Container nodes invisible to host or other terminalsContainer launched with default bridge network or mismatched domainRecreate 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 containerContainer is stopped (Exited) or named differentlyCheck docker ps -a and resume with docker start ros2_jazzy
ros2: command not found in VS Code terminalShell opened without reading ~/.bashrc or setup line missingEnsure source /opt/ros/jazzy/setup.bash is in container ~/.bashrc
Slow 3D rendering in Gazebo inside containerX11 forwarding falling back to CPU software renderingRun heavy 3D simulators on the host OS while running ROS 2 nodes in the container over --net=host

Common mistakes

  • Running docker run in every new terminal window—creating separate isolated containers—or using docker attach and accidentally stopping the container with Ctrl+C.
  • Executing colcon build inside the container as root without matching the host UID/GID, which locks the bind-mounted ~/ros2_ws directory with root ownership.
  • Installing the ROS, Python, and XML extensions only on the host VS Code instance instead of installing them inside the Dev Container remote environment.

Pre-flight checklist

  • Included –net=host, –ipc=host, DISPLAY, /tmp/.X11-unix bind mount, and workspace volume (-v) in the container launch configuration
  • Created a non-root container user matching the host UID and GID (typically 1000:1000) to preserve file permissions
  • Confirmed that three separate docker exec -it terminals report the same ROS_DOMAIN_ID and ros2 topic list output
  • Verified that ms-iot.vscode-ros, ms-python.python, and redhat.vscode-xml are active inside the container in VS Code

Frequently asked questions

Why should I use docker exec instead of docker attach for multiple terminals?
docker attach connects your terminal directly to the container’s primary process (PID 1). Pressing Ctrl+C to stop a ROS 2 node or typing exit in an attached session can terminate the entire container. In contrast, docker exec -it spawns an independent shell process inside the running container, so closing that terminal leaves the container and other terminals untouched.
When should I choose Attach to Running Container versus a .devcontainer configuration?
Attach to Running Container (Method A) is ideal when a container is already running via docker run or docker compose and you want to open an editor inside it immediately. A .devcontainer/devcontainer.json file (Method B) is better for team repositories because it checks the Dockerfile, run flags, volume mounts, and required VS Code extensions into version control.
Do I still need ROS 2 installed on the host machine when using Docker and Dev Containers?
No. The host machine only requires Docker Engine and VS Code with the Dev Containers extension. All ROS 2 compilers, colcon, rviz2, and message packages live inside the container. Only heavy GPU workloads like Gazebo simulations are sometimes kept on the host and bridged to the container via –net=host.

Sources & verification

  1. Docker Docs — docker container exec
  2. VS Code Docs — Developing inside a Container
  3. Docker Hub — Official ROS Images
  4. ROS 2 Jazzy — Configuring ROS 2 environment

Last verified: