Docker-Based ROS 2 Installation Guide
This note provides a ROS 2 Humble installation workflow based on Dockerfile + Docker Compose. Follow the steps below to complete the environment setup.
1. Prepare the Directory Structure
The recommended directory structure is:
ros2_docker/ros2_docker/ws/ros2_docker/ws/src/ros2_docker/Dockerfileros2_docker/compose.yml
2. Write the Dockerfile
Create and edit Dockerfile in the project root:
nano Dockerfile
FROM ros:humble-ros-base
ENV DEBIAN_FRONTEND=noninteractive
# ============================ Configure APT mirror (optional) ============================
# ========
# 1. Permanently switch APT source to USTC (ubuntu-ports, arm64-friendly)
# ========
RUN set -eux; \
. /etc/os-release; \
codename="${VERSION_CODENAME:-jammy}"; \
\
cat > /etc/apt/sources.list <<EOF
deb https://mirrors.ustc.edu.cn/ubuntu-ports/ ${codename} main restricted universe multiverse
deb https://mirrors.ustc.edu.cn/ubuntu-ports/ ${codename}-updates main restricted universe multiverse
deb https://mirrors.ustc.edu.cn/ubuntu-ports/ ${codename}-backports main restricted universe multiverse
deb https://mirrors.ustc.edu.cn/ubuntu-ports/ ${codename}-security main restricted universe multiverse
EOF
# =======
# 2. (Strongly recommended) Configure APT timeout and retries to reduce network jitter impact
# =======
RUN printf 'Acquire::Retries "8";\nAcquire::http::Timeout "30";\nAcquire::https::Timeout "30";\n' \
> /etc/apt/apt.conf.d/99retries
RUN apt-get update && apt-get install -y --no-install-recommends \
ros-humble-desktop \
&& rm -rf /var/lib/apt/lists/*
# Save and exit the editor
3. Write compose.yml
Create and edit compose.yml in the project root:
nano compose.yml
services:
ros2:
build:
context: .
dockerfile: Dockerfile
container_name: ros2_desktop
init: true
tty: true
stdin_open: true
network_mode: host
privileged: true
environment:
- DISPLAY=${DISPLAY}
- QT_X11_NO_MITSHM=1
- XAUTHORITY=/tmp/.docker.xauth
- ROS_DOMAIN_ID=0
- RMW_IMPLEMENTATION=rmw_fastrtps_cpp
volumes:
- /dev:/dev
- ./ws:/root/ws
- /tmp/.X11-unix:/tmp/.X11-unix:rw
- /tmp/.docker.xauth:/tmp/.docker.xauth:rw
working_dir: /root
command: >
bash -c "
source /opt/ros/humble/setup.bash &&
exec bash
"
# Save and exit the editor
4. Build the Image and Start the Container
sudo docker compose build
sudo docker compose up -d
# To stop the container: docker compose stop
sudo docker exec -it ros2_desktop bash
cd ws
colcon build
source install/setup.bash
5. Verify the Installation
# Verify whether installation is successful
xhost +local:docker
rviz2
6. Additional Handling if Verification Fails
If verification fails in the previous step, run the following commands for supplementary installation and environment setup:
apt update
apt install -y ros-humble-rviz2
nano ~/.bashrc
# Add content in the following order
source /opt/ros/humble/setup.bash
source ~/ws/install/setup.bash
rviz2