Getting Started with ROS 2 Programming
local graph
Chapter 2 — Getting Started with ROS 2 Programming
Section titled “Chapter 2 — Getting Started with ROS 2 Programming”In the previous chapter, we discussed the fundamentals of the ROS framework and its important features. We made a detailed comparison between ROS 1 and ROS 2 architecture and discussed why we must migrate from ROS 1 to ROS 2. We also saw the work of DDS, which is the core part of ROS 2. We listed popular DDS vendors and different layers of ROS 2, which connect to ROS 2 and DDS. I hope that the chapter provided an overview of ROS 2 architecture and its relevance in robotics software.
This chapter will give you a practical overview of how to quickly set up ROS 2 on Ubuntu 24.04 on any computer and start working on it. We will explore multiple ways to set up ROS 2 on our computers. After setting up ROS 2, we will start familiarizing ourselves with its basics. Then, we will start discussing ROS 2 concepts using its tools, packages, workspace, and Turtlesim, a 2D simulator that can be used to learn about ROS 2 concepts. Ultimately, we will see a detailed discussion of ROS 2 client libraries, which help developers write ROS 2-based applications in multiple programming languages. After understanding the ROS 2 client libraries, we will learn how to start developing robot software using ROS 2.
Here are the main topics we are going to discuss:
- Mastering ROS 2 installation
- Mastering ROS 2 tools and concepts with Turtlesim
Technical requirements
Section titled “Technical requirements”To follow this chapter, it is better to have a computer/embedded board (e.g., Raspberry Pi, Jetson board, etc.) with Ubuntu 24.04 LTS installed or any other Ubuntu version. If you don’t have Ubuntu on your machine, make sure you have Windows 11/10 or macOS.
The reference materials for this chapter can be found in the Chapter02 folder of the following GitHub repository: https://github.com/PacktPublishing/Mastering-ROS-2-for-Robotics-Programming/tree/main/Chapter02.
Mastering ROS 2 installation
Section titled “Mastering ROS 2 installation”When you read this section’s title, you may wonder what we must master to install software on a computer. I think you will get clarity after going through this section completely.
Most robots’ computers run on a Linux distribution, most commonly Ubuntu. The robot computers were chosen based on the robotic application requirements. They can be industrial PCs with x86_64 architecture or ARM64-based compute modules such as Jetson Orin or Raspberry Pi.
As you know, we will deploy the robot application on the robot computer. However, robot software development will mostly happen on a developer workstation or laptop, which can be loaded with Windows, Ubuntu, or macOS.
Can ROS 2 be installed on all platforms? Yes. It is possible with the help of tools such as Docker, VirtualBox, VMware, UTM, and so on. Let’s explore different ways of installing ROS 2 on a robot and in our development machine.
Installing Ubuntu 24.04 LTS and ROS 2 Jazzy
Section titled “Installing Ubuntu 24.04 LTS and ROS 2 Jazzy”As you have already seen in Chapter 1, this book mainly focuses on ROS 2 Jazzy, which is primarily compatible with Ubuntu 24.04 LTS (LTS stands for Long-Term Support) [1]. ROS 2 Jazzy will not install on any Ubuntu version other than 24.04. So, let’s explore how to set up Ubuntu 24.04 in our development machine and the robot.
Installing Ubuntu 24.04 LTS
Section titled “Installing Ubuntu 24.04 LTS”There are multiple ways to set up Ubuntu 24.04 on a computer. Here are some references to get started with Ubuntu 24.04 installation for setting up ROS 2 Jazzy:
- Setting up Ubuntu in the development workstation (x86_64/ARM64 architecture):
- Installing Ubuntu in dual boot: Suppose you have a development workstation with an Intel or AMD processor with an x86_64 architecture-based processor. In that case, you can download the official ISO image from the Ubuntu website, flash it into a thumb drive, and install it on your real machine with Windows or another OS. If you already have another operating system, such as Windows, on your machine, you can do a dual-boot installation by following these instructions [2]. Make sure you are opting for a manual installation from the instructions. The manual installation will allow us to format the desired partition on the drive. Installing Ubuntu on a real machine will perform better than any other virtualization method because it works without other software layers. If you use macOS on Apple Silicon, you can check out UTM [3], which is easy virtualization software for installing Ubuntu 24.04 on a Mac with an M1 series chipset. This software allows us to install the complete desktop version of Ubuntu and work with it without rebooting the machine. Switching between multiple virtual OS installations and the host OS, which can be Windows or macOS, is straightforward.
- Installing Ubuntu on VirtualBox/VMware/UTM/WSL 2: Installing Ubuntu on a real machine is sometimes risky for beginners. Due to mistakes, it can sometimes crash the OS and not boot after that. If you are comfortable working with another OS such as Windows 10/11 or macOS, you can install Ubuntu virtually on these operating systems. Software such as VirtualBox and VMware can be installed on these operating systems, and Ubuntu can be installed using this software. These types of software are called virtualization software. You can download VirtualBox from reference [4], and you can download VMware from [5]. VirtualBox is free to download and use, and VMware Workstation is free for personal use, but not for commercial applications. The detailed instructions on installing Ubuntu 24.04 on VirtualBox can be found in reference [6], and the detailed instructions to set up Ubuntu 24.04 in VMware can be found in [7]. If you use macOS on Apple Silicon, you can check out UTM [8], an easy virtualization software that can install Ubuntu 24.04 on macOS with the M1 series chipset. This software allows us to install the complete desktop version of Ubuntu and work with it without rebooting the machine. Switching between multiple virtual OS installations and the host OS, which can be Windows or macOS, is straightforward. Windows 10/11 comes with Windows Subsystem for Linux (WSL), an additional feature in Windows that allows developers to run Linux environments such as Ubuntu without the need for separate virtual machines. Here is the reference to set Ubuntu 24.04 LTS in Windows WSL 2: [9]. WSL 2 is good for learning and experimenting with Ubuntu without having a dual-boot setup.
- Installing Ubuntu on Docker: Docker [10] is an operating system-level virtualization platform. The main difference between virtualization software, such as VirtualBox, and Docker is that VMS virtualizes a complete OS. In contrast, Docker containers virtualize the application layer on top of the host OS. It uses a containerization concept, which can isolate the application and its dependencies in portable and lightweight units called containers. The containers share the host OS kernel. We need a host OS such as Ubuntu, Windows, or macOS to install Docker. Docker is comparatively lightweight and ideal for ROS 2 application deployment in robots. Many Docker images are hosted publicly in Docker Hub [11]. Docker images are files that contain all the libraries and dependencies, and containers are the running instances of an image. Using the Docker CLI, we can download, manage, and run different Docker images. The upcoming section will discuss Docker setup because it is a useful technology for deploying ROS 2-based robotic applications. It will also show how to deploy a robot application efficiently using Docker.
- Setting up Ubuntu in your robot: Most robots have x86_64 or ARM64-based boards such as Raspberry Pi, Jetson Orin, or an industrial PC with an Intel or AMD processor. We can install Ubuntu on these machines. If we have an x86_64 machine, the installation procedure is straightforward; you can follow the above instructions. However, if we have embedded boards such as Raspberry Pi or Jetson series boards, the instructions are different. Ubuntu is customized for these boards, and we can see some references for installing Ubuntu on these boards. The setup instructions for setting Ubuntu 24.04 in Raspberry Pi 5 can be found in reference [12], and you can find a reference for Ubuntu installation in Jetson boards here: [13].
We have seen different references for installing Ubuntu 24.04 LTS in robots and our development workstation. Now, let’s see how we can install ROS 2 Jazzy on Ubuntu.
Installing ROS 2 Jazzy on Ubuntu 24.04 LTS
Section titled “Installing ROS 2 Jazzy on Ubuntu 24.04 LTS”This section provides detailed instructions for installing ROS 2 Jazzy on Ubuntu 24.04 LTS. This instruction will work on x86_64 and ARM64 machines.
To make the installation easy, you can also find a shell script to automate this installation and uninstallation procedure. You can find the script ros2_install_jazzy.sh in the Chapter02 folder for installing ROS 2 Jazzy and ros2_uninstall_jazzy.sh for uninstalling the same.
You can run the following commands inside the Chapter02 folder for installing ROS 2 Jazzy with an automated shell script:
chmod +x ros2_install_jazzy.sh./ros2_install_jazzy.shHere is the command for uninstalling ROS 2 Jazzy in the future:
chmod +x ros2_uninstall_jazzy.sh./ros2_uninstall_jazzy.shHere is the official link for installing ROS 2 Jazzy in Ubuntu, RHEL, and Windows 10: [14]. The recommended OS for installing ROS 2 Jazzy is Ubuntu 24.04 Noble Numbat. For easy setup, it is recommended that you install via the Debian package manager.
The following section explains the different steps in the ROS 2 Jazzy installation, which are mentioned in the installation script.
Setting the locale of your system
Section titled “Setting the locale of your system”It is important to set the language and character encoding in Ubuntu before installing ROS 2. This is because DDS uses UTF-8 (short for Unicode Transformation Format-8 bit) as the character encoding of IDL type string. To check the UTF-8 encoding of Ubuntu 24.04, you can use the locale command in Ubuntu. The locale command in Ubuntu 24.04 (and other Linux distributions) is used to display and set the system’s locale information, which defines how data such as dates, times, numbers, currency, and text are formatted and displayed based on regional and language preferences. During installation, the Ubuntu locale is automatically generated based on the language preference we provide.
Here are the steps for setting the locale in your machine:
- Open a new terminal in Ubuntu and execute the following command to check your Ubuntu’s current locale:
locale
You will get the following output as the first line if the UTF-8 is properly set:
LANG=en_US.UTF-8..................................If it is already set, you don’t have to execute the following command, otherwise, you have to execute the command to set the encoding.
- This command will update the list of Ubuntu packages from the server and install the
localescommand if it is not installed already:sudo apt update && sudo apt install locales - The following command ensures that both the basic
en_USanden_US.UTF-8locales are generated and available for use on your system:sudo locale-gen en_US en_US.UTF-8 - After generating locales, we can set the system-wide locale using the following command:
sudo update-locale LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8export LANG=en_US.UTF-8
- We are done with configuring the locale now; you can verify the settings by executing the
localecommand again:locale # verify settings
After setting the locale in your machine, the next step is to configure Ubuntu repositories. In Ubuntu, there are many software packages available to download. Some packages are free, and some packages are not. The packages are distributed in four main repositories, as follows:
main: This is supported by Canonical, which is the creator and maintainer of Ubuntu. The packages available in themainrepo will be free and open-source software.universe: This repository has community-maintained free and open-source software.restricted: This repository contains proprietary drivers or firmware that are not open source, but are still freely redistributable. These are typically essential for enabling specific hardware functionality.multiverse: This repository contains software restricted by copyright, licensing, or legal issues, and may not be freely usable in all regions or for all purposes.
ROS 2 Jazzy packages are in the Ubuntu universe repository, so we have to enable the universe repository first.
Enabling the repository in Ubuntu
Section titled “Enabling the repository in Ubuntu”Ubuntu provides software tools to manage and configure software sources or repositories. These tools help to add or remove third-party software repositories, manage GNU Privacy Guard (GPG) keys [15] for those repositories, and configure the systems’ software sources. We have to install software-properties-common first to enable the universe repository.
We can install the software-properties-common package to get those tools to manage any repository in Ubuntu:
sudo apt install software-properties-commonAfter installing this package, we will get a command-line tool called add-apt-repository. This command allows us to easily add/remove repositories or Personal Package Archives (PPAs). A PPA is like a personal software store where developers upload their software [16].
Here is how we use add-apt-repository to enable the universe repository:
sudo add-apt-repository universeAfter enabling the universe repository, let’s add the ROS 2 GPG key and apt sources list.
Adding the ROS 2 Jazzy GPG key and apt sources list
Section titled “Adding the ROS 2 Jazzy GPG key and apt sources list”GPG keys are like digital locks used to keep software safe. They are used to verify the authenticity and integrity of downloaded packages. They ensure that when you download software (such as from a PPA), it’s really from the person or company that made it and hasn’t been changed by anyone else.
The source list is a system file in Ubuntu that contains information about the software repositories (sources) that our system can use to download and install packages using the apt package manager. This file tells Ubuntu to look for software updates and new software. The location of the sources list file is in /etc/apt/sources.list.
ROS 2 provides a package called ros2-apt-source, which can provide keys and apt source configuration for the various ROS repositories. Installing this package will configure ROS 2 repositories in our system. The repository configuration will be updated automatically when new packages are released to the ROS repositories. We use a software tool called curl to download this package and save it into a specific path.
The following command will update the Ubuntu package list from the repository and install curl. When it does the updating, it will include the universe repository package list as well:
sudo apt update && sudo apt install curl -yAfter installing curl, we can download the latest version of ros2-apt-source package. The following command fetches the latest version of the ROS APT source configuration.
export ROS_APT_SOURCE_VERSION=$(curl -s https://api.github.com/repos/ros-infrastructure/ros-apt-source/releases/latest | grep -F "tag_name" | awk -F" '{print $4}')After fetching the latest version, we can download ros2-apt-sources using the curl command.
curl -L -o /tmp/ros2-apt-source.deb "https://github.com/ros-infrastructure/ros-apt-source/releases/download/${ROS_APT_SOURCE_VERSION}/ros2-apt-source_${ROS_APT_SOURCE_VERSION}.$(. /etc/os-release && echo $VERSION_CODENAME)_all.deb"Now we can install the ros2-apt-source using the following command
sudo apt install /tmp/ros2-apt-source.debWe are now done with saving the ROS 2 Jazzy GPG keys and apt sources list. In the next section, we will see how to install the ROS 2 development tools.
Installing development tools
Section titled “Installing development tools”Installing development tools in ROS 2 helps automatically format code written in C++/Python, analyze potential errors or inefficiencies before compiling or running, provide build tools/scripts to set up and build ROS 2 packages, and finally, provide tools for identifying bugs and running unit tests on ROS code.
The following command installs these tools in Ubuntu 24.04:
sudo apt update && sudo apt install ros-dev-toolsAfter installing ROS development tools, let’s install ROS 2 Jazzy.
Installing ROS 2 Jazzy
Section titled “Installing ROS 2 Jazzy”The first step before installing ROS 2 Jazzy packages is to update the list of packages and upgrade the packages that have already been installed. The following commands will update the latest ROS 2 packages and upgrade all the Ubuntu packages so our Ubuntu will be up to date with the currently installed packages:
sudo apt updatesudo apt upgradeAfter doing the update and upgrade operations, you can finally install ROS 2 Jazzy. There are two options: ros-jazzy-desktop installation or ros-jazzy-base installation. If we need most of the features in ROS 2, go with the desktop installation, which is the recommended method. If you only need the core communication libraries, you can go with the ros-jazzy-base installation. It will not have any GUI tools and contains mainly communication libraries, message packages, and command-line tools.
Here is the command to install both methods. You can choose one among these:
- Desktop installation:
sudo apt install ros-jazzy-desktop
- ROS-Base installation:
sudo apt install ros-jazzy-ros-base
The installation of the desktop version of ROS 2 will take longer, depending on the internet speed and PC specification. The ROS-Base version will be installed much faster and it is more preferred in embedded boards.
Congratulations, you are done with the ROS 2 Jazzy installation. So, is it completely done? No. To start working with ROS 2 commands and tools, it is important to source the environment by executing the following command:
source /opt/ros/jazzy/setup.bashThe sourcing of this file makes the ROS 2 tools and packages visible in the current terminal. This command is very important because, without it, ROS 2 commands will not be visible to users.
Here is an easy way to source this line every time we open a new terminal. This will be the best way to start learning and experimenting with ROS 2:
echo "source /opt/ros/jazzy/setup.bash" >> /home/$USER/.bashrcThis will write source /opt/ros/jazzy/setup.bash to the ~/.bashrc file, which is the configuration file of the Linux terminal. This script will execute whenever a new terminal is created, so we don’t have to execute the ROS 2 source command every time we open a new terminal.
Now we have completed all the steps in the installation of ROS 2 Jazzy in Ubuntu 24.04, we can run a test to ensure the ROS 2 environment is set up properly:
- Open the terminal application in Ubuntu and add one more tab.
- In the first tab, run this command:
ros2 run demo_nodes_cpp talker
- In the second tab run this command:
ros2 run demo_nodes_py listener
The following image shows the output of the test if everything is configured correctly.

Figure 2.1: ROS 2 talker and listener demo
Figure 2.1: ROS 2 talker and listener demo
The above example is simply a publisher/subscriber demo using ROS 2. If this is working fine, it means the installation and configuration are working. If it is not working or if you are getting errors, make sure the sourcing of ROS 2 is correct. You can press Ctrl + C to cancel each of the running nodes.
In this section, we discussed the installation of ROS 2 Jazzy in Ubuntu 24.04 LTS. Now let’s explore how we can set up ROS 2 Jazzy in other OSs such as Windows and macOS, mainly for development.
Installing ROS 2 Jazzy on Windows 11/10
Section titled “Installing ROS 2 Jazzy on Windows 11/10”We can install ROS 2 Jazzy on Windows in multiple ways. Here are the main methods we can follow:
- Installing ROS 2 Jazzy in VirtualBox/VMware: We have already discussed installing Ubuntu 24.04 LTS on virtualization software such as VirtualBox. To install ROS 2 Jazzy on it, we can follow the same instructions we have discussed for Ubuntu 24.04 LTS. This is very easy to set up and safe for experimenting with ROS 2 as well. Even if the guest OS crashes, it will not affect the main host OS, which is Windows here.
- Installing ROS 2 Jazzy in WSL 2: WSL is a feature in Windows 10/11 that allows the running of a Linux environment on a Windows machine without the need for a virtual machine or dual-boot setup. Here is the official tutorial on how to enable WSL on Windows: [17]. The first version was WSL 1, and the latest is WSL 2. WSL 2 has more features than WSL 1. Using WSL 2, we can install new versions of Ubuntu, such as Ubuntu 24.04 and 22.04. The same installation instructions for ROS 2 Jazzy in Ubuntu 24.04 LTS can be followed to install ROS 2 Jazzy on WSL 2. It is not only command-line-based but can also visualize GUI tools. There is also easy file sharing between Windows and WSL 2.
- Installing ROS 2 Jazzy in Windows 10 (without any virtualization): We can install ROS 2 Jazzy natively on Windows 10 but not on Windows 11. This method does not use WSL, but everything runs natively without any layers. The setup instructions are tedious and time-consuming, but if we really want to integrate ROS 2 with any Windows-native application, this is the path to go. Here is the reference for installing ROS 2 Jazzy on Windows 10: [18].
We have explored methods to set up ROS 2 Jazzy on Windows 10/11; now we can discuss methods to install ROS 2 Jazzy natively or virtually on macOS.
Installing ROS 2 Jazzy on macOS
Section titled “Installing ROS 2 Jazzy on macOS”We can install ROS 2 Jazzy on macOS in multiple ways. Here are the main methods we can follow:
- Installing ROS 2 Jazzy in VirtualBox/VMware/UTM: If you are using a Mac with an Intel processor, you can install VirtualBox and VMware and install Ubuntu 24.04 LTS and ROS 2 Jazzy on it. If you are using a Mac with an Apple silicon chipset such as M1/M2/M3, you can use VMware or UTM [19] to install Ubuntu 24.04 LTS.
- Installing ROS 2 Jazzy on macOS (source code): If you are interested in running ROS 2 code natively on macOS without any virtualization, then this is the way to go. You can download and build the source code and run it using the following procedure: [20]. These steps are a bit complex, but if your application really needs native support, it’s better to follow this approach.
- Installing ROS 2 Jazzy on Mac (dual boot): In this option, we are not installing on macOS, but we are performing dual boot. We can install Ubuntu 24.04 LTS along with macOS on an Intel-based Mac directly using a USB flash drive [21]. You can follow the ROS 2 Jazzy installation instructions thereafter. If you are using an Apple Silicon-based machine, it’s better to check Ubuntu Asahi [22]. This is a community project porting Asahi Linux to Ubuntu, which aims for stability and full-featured installation with Apple silicon hardware.
We have seen setting-up instructions and references for ROS 2 Jazzy on Windows, Linux, and MacOS. Here is another method for setting up ROS 2 Jazzy quickly on all operating systems.
Installing ROS 2 Jazzy in Docker
Section titled “Installing ROS 2 Jazzy in Docker”Docker [23] is an open-source technology that helps software developers quickly develop and deploy Windows, Linux, and macOS applications. Docker is also widely used in robotics software development and deployment. The main advantage of using Docker is that we can quickly develop and deploy your ROS-based application in any ROS distribution and Linux distribution. Even if your host OS is Ubuntu 20.04, you can develop ROS 2 applications in ROS 2 Jazzy (which uses Ubuntu 24.04) using Docker. It will help to build and test your ROS 2 application in different ROS 2 distributions. The only requirement is to install Docker software on these operating systems. Docker is one important technology we use in this book. We will discuss Docker in more detail in this section.
Docker is a software tool to create, deploy, and run applications using a technology called containers. Each container in Docker has a lightweight instance of the software environment to run our application. The environment has code, libraries, and dependencies. This helps containers work in different environments. Each container has no separate OS, like the VM we have seen before. The containers work alongside the host Linux kernel and create an abstraction to run different environments. So, like a VM, we do not have to install a full OS to run an application. Before diving into Docker, let us see how to install it on Ubuntu 24.04 LTS as the host machine.
The official installation of Docker is on their website [24]. In this book, we have added an automatic script to do the same. It will install Docker in Ubuntu 24.04 as well as the NVIDIA Container Toolkit [25]. The NVIDIA Container Toolkit enables users to build and run GPU-accelerated containers that will work alongside Docker.
Installing Docker and the NVIDIA Container Toolkit
Section titled “Installing Docker and the NVIDIA Container Toolkit”Follow these steps to install Docker and the NVIDIA Container Toolkit:
- Open the book’s GitHub repository and navigate to
Chapter02|ros2_jazzy_docker/docker_setup_scripts. You can findsetup_docker_ubuntu.shthere. You can run this script by opening a terminal inside this folder:chmod +x setup_docker_ubuntu.sh./setup_docker_ubuntu.sh
This script helps install all the dependencies of Docker. If you have an NVIDIA graphics card and driver installed properly, it will install the NVIDIA Container Toolkit, which gives the container graphics acceleration.
- If everything is installed properly, you can check that Docker is running in the background using the following command:
systemctl status docker
You will get the following output if everything is properly set up:

Figure 2.2: Checking Docker status
Figure 2.2: Checking Docker status
- If the Docker status is
active, then you can check thedockercommand in the terminal to make sure everything is okay:docker info
You will get the following output. This is all the system details of Docker:

Figure 2.3: Checking Docker information
Figure 2.3: Checking Docker information
After making sure everything is okay on our PC, we can start working in ROS 2 Jazzy using Docker and discuss the underlying concepts of Docker along the way.
Running Docker with ROS 2 Jazzy
Section titled “Running Docker with ROS 2 Jazzy”We must perform a few steps before starting to work with ROS 2 Jazzy on Ubuntu 24.04 LTS. The steps are elaborated on in the following subsections.
Step 1: Pulling the base image and building a custom Docker image
Section titled “Step 1: Pulling the base image and building a custom Docker image”The first step to getting started with Docker is pulling a base image from Docker Hub or another source. Let’s first understand what Docker and base images are.
Docker images are files that contain all the application code, dependencies, and runtime environment. We can say that Docker images are templates for creating a Docker container. A base image is the base Docker image we are using to build our Docker image. For example, we can take the ROS 2 Jazzy Docker image as a base image, and using that, you can create your image with all dependencies.
Docker Hub [26] provides developers with free access to public Docker images and allows them to upload their own Docker images. These Docker images allow developers to use them as a base image and create containers out of them.
After installing Docker on your machine, you can directly pull the Docker image of ROS 2 Jazzy from Docker Hub. Open Robotics publishes all the ROS 1 and 2 Docker images in their account [27]. You can pull any image from their account.
The following command helps to pull the base image of Jazzy from Docker Hub. This will take you directly into the ROS 2 Jazzy environment without installing anything:
docker pull osrf/ros:jazzy-desktop-fullAfter entering this command, you can see the image is getting downloaded, and it will take some time based on the internet speed. Once everything is downloaded, you will have the base image of ROS 2 Jazzy. The next step is to create a container using this image. As we already discussed, Docker images are like templates for the container, so once a container gets started, we will get the ROS 2 Jazzy environment inside it. We mostly work inside the container using a shell because most base images have a lightweight environment, which does not include a desktop environment as we see in Ubuntu 24.04 LTS.
After getting Jazzy’s Docker image, we can start creating a container out of it. The following section discusses the steps.
Step 2: Creating a container out of the ROS 2 Jazzy image
Section titled “Step 2: Creating a container out of the ROS 2 Jazzy image”To create a container, you can use the following command:
docker run -it --name master_ros2 osrf/ros:jazzy-desktop-full bashAfter running this command in your terminal, you will be able to see a new terminal with a different user, which might be a root user, like the following:
root@eafa922c9072:/#This line is the shell of the ROS 2 Jazzy container with the name master_ros2. If you check the command above, you can see that we use the docker run command to create a container. We must add the image name; we can also mention the container name using the --name argument. The --it argument in Docker helps interact with the container by providing text commands through the bash shell. The bash shell tells the Docker container to run the bash command once it starts. So, this command creates a Docker container with an interactive bash shell with a container name of master_ros2. The container’s name is optional here. If you do not include a name for the container, it will randomly assign a name. It will be better to put a name so we can start, stop, and delete this container easily.
After creating the container from the image, you will get a ROS 2 Jazzy environment where you can do anything. Your progress will be lost if you delete the container. The changes you make in the container are cached, so you can start and stop the container without losing data. Only rebuilding it will cause you to lose any data that is not mounted on the host system.
You can perform the following test to make sure ROS 2 Jazzy is working correctly.
Execute the sample publisher node in ROS 2, which publishes a Hello World string. This must execute in the Docker terminal:
root@eafa922c9072:/# ros2 run demo_nodes_cpp talkerIf you get a message such as the following, it means it is good to go:
[INFO] [1726068567.949579583] [talker]: Publishing: 'Hello World: 1'[INFO] [1726068568.949567985] [talker]: Publishing: 'Hello World: 2'[INFO] [1726068569.949575774] [talker]: Publishing: 'Hello World: 3'Now, we can run the next command to subscribe to this message. To run a new shell in Docker, you can follow the next section.
Step 3: Running a new command in the ROS 2 Jazzy container
Section titled “Step 3: Running a new command in the ROS 2 Jazzy container”After creating a container and accessing the shell, we executed the publisher program in ROS 2, and we can see it is working. Now, how do you access another terminal of this container and run the subscriber code? That is where docker exec commands come in. The docker exec commands help us run another program or command in the same container. So, take a new terminal in your host OS and execute the following command to get access to the container terminal:
docker exec -it master_ros2 bashThis command attaches a new shell to the running container. Now, you can source the ROS 2 Jazzy environment using the following command. This command makes the ROS 2 tools visible in the current terminal.root@eafa922c9072:/# source /opt/ros/jazzy/setup.bashAfter sourcing this command, you can run the listener node:
root@eafa922c9072:/# ros2 run demo_nodes_cpp listenerYou will get the following output if everything is working well:
[INFO] [1726069883.429240302] [listener]: I heard: [Hello World: 3][INFO] [1726069884.429221835] [listener]: I heard: [Hello World: 4][INFO] [1726069885.429212317] [listener]: I heard: [Hello World: 5]Press Ctrl + C to terminate each running node and press Ctrl + D to exit from the shell. After exiting the shell, the container may still be running in the background. You can stop the container using the command in the next section.
Step 4: Starting, stopping, and removing the container
Section titled “Step 4: Starting, stopping, and removing the container”Here is the command to stop the running container:
docker stop master_ros2If you want to find the status of all containers in your computer, use:
docker ps –aThis will show all the existing containers and their status, such as whether it is stopped or running. After stopping the container, if you want to start it again, you can use the docker start command with the container name:
docker start master_ros2After starting the container, you can attach a shell using the docker exec command and access the container’s shell:
docker exec -it master_ros2 bashSo, once you create a container, you do not need to create it again unless you have any changes in the Docker image. You can simply start and stop the container whenever you want.
If you want to remove the current container, you can use the docker rm command. Make sure you stop the container before you delete it:
docker stop master_ros2docker rm master_ros2After deleting the container, you must create a new one using the docker run command again to create a container.
We have explored the basic commands in Docker. Here is a reference to a Docker command cheat sheet that you can use for learning more commands: [28]. Now, let us discuss another important concept in Docker, called a Dockerfile.
Dockerfile for ROS 2 Jazzy
Section titled “Dockerfile for ROS 2 Jazzy”A Dockerfile is a text file containing instructions used to build a custom Docker image. It defines how the custom Docker image should be built. So, why do we need to build a custom Docker image? Imagine you have developed some robot software using ROS 2; running this software requires some dependencies to be installed. The ROS 2 Jazzy base image we used earlier may not have all the dependencies installed. In this scenario, we can write a Dockerfile by putting ROS 2 Jazzy as the base image and adding the dependencies and environment to create a new custom Docker image. The Dockerfile helps us create custom Docker images with dependency packages for running the application. It is similar to a recipe, like a set of instructions for producing an image. We can write the Dockerfile using Dockerfile-specific instructions and build this file using the docker build command.
Here is what a basic ROS 2 Jazzy Dockerfile looks like:
#Base ImageFROM osrf/ros:jazzy-desktop-full#Update and upgrade Ubuntu package and install pipRUN apt update && apt upgrade -yRUN apt install -y python3-pip#Execute command, bash when it create the containerCMD ["/bin/bash"]You can switch to the Chapter02 | ros2_jazzy_docker/docker_basics folder and find this file as a Dockerfile. The name Dockerfile is the default name of all Dockerfiles, but you can name it as you prefer, such as Dockerfile.basic, Dockerfile.master_ros2, and so on if you want to keep multiple Dockerfiles for different applications. During the Docker image building, you can mention this Dockerfile name, and it will build the corresponding Dockerfile.
Let’s first build the custom Docker image and then explore how the Dockerfile works.
Here is the command used to build a Dockerfile and create a custom image. Open a terminal from the same folder where the Dockerfile is placed and execute this command:
docker build -f Dockerfile -t test_ros2:v0.1 .This command reads the Dockerfile, which is mentioned with the -f argument, and -t to mention the image name and its tag. The tag is optional, but it is better to put a tag on each image to identify the version if there are any changes in the Dockerfile. You can find a dot (.) at the end, which refers to the current directory. The Dockerfile will now look for files to copy to the container with respect to this directory.
After a successful build, you can be able to find messages like this in the terminal:

Figure 2.4: Dockerfile build messages
Figure 2.4: Dockerfile build messages
After building the image, we can create the container using the docker run command. as we have done previously:
docker run -it --name test_ros_dev test_ros2:v0.1After creating the container, you can use the docker exec command to access more shells.
You now have an idea of how to build a ROS 2 Jazzy image by writing our Dockerfile, so let’s walk through the Dockerfile we mentioned above.
The Dockerfile starts from a ROS 2 Jazzy base image. The FROM instruction in the Dockerfile is used to mention the base image we are using. After that, we update and upgrade the packages of the base image. This operation uses the RUN instruction in the Dockerfile. Using the RUN instruction, we can install packages in the base image. The update & upgrade operation itself makes the base image a custom image because the new image has the latest packages; now, we are using RUN instruction to install a new Ubuntu package called python3-pip into the custom image. Finally, the CMD instruction specifies the command we must execute when we start the container.
This command can be overridden by providing the command at the end of the docker run command. There is a similar command called ENTRYPOINT in the Dockerfile, which does the same function, but the command cannot be overridden in docker run.
Let us look at some more complex Dockerfiles for ROS 2-based development. You can find basic Dockerfiles that will be good for starting ROS 2 development. If you switch to Chapter02 | ros2_jazzy_docker/docker_basics, you will find Dockerfile.basic. The default user in the ROS 2 Jazzy base image is the root user. This Dockerfile can create a new user, which restricts the permissions and is safer than the root user. The root user has full permission to do anything in Docker. Sticking to a normal user while developing and using the sudo command to get root access will be better.
To build this file and use it, you can use the same Docker commands that you used for the first Dockerfile example.
So far, we have seen Docker containers that interact with shell commands. What about using GUI applications inside the Docker container? Yes, that is possible as well. In the next section, we can see how to run ROS 2 tools with GUI enabled.
Enabling GUI in a ROS 2 Jazzy container
Section titled “Enabling GUI in a ROS 2 Jazzy container”In this section, we will look at how to enable GUI support in Docker. After enabling GUI support, we can work on the GUI and command-line tools of ROS 2 Jazzy. So, let’s get started.
Go to Chapter02 | ros2_jazzy_docker/docker_gui; inside this, you can find a similar Dockerfile to Dockerfile.basic. The name of the Dockerfile is Dockerfile.master_ros2. These two files are almost identical, but the difference is in the docker run command. You can see the shell script along with Dockerfile.master_ros2 for building images, creating, starting, stopping, and removing the Docker containers. This will make the process easier than remembering all the Docker commands. Also, all the scripts will take command-line arguments in which we can mention the Dockerfile, container name, and so on to build the Docker image and run the container.
Building the Docker image
Section titled “Building the Docker image”We have a script called build_image.sh, which accepts several arguments such as Docker image name, username, and so on, and uses the docker build command to build the Dockerfile.
We will discuss the usage of the script inside the folder first. Before running the script, create a folder in your home folder called master_ros2_ws/src to keep your ROS 2 packages. You can use the following command to do this:
mkdir -p ~/master_ros2_ws/srcAfter creating this folder, you can start building the Docker image using the following command. Make sure you are executing inside the docker_gui folder:
./build_image.sh ros2_gui:v0.1 master_ros2_ws robotIn this script, the first argument is the custom Docker image name with version, the second argument is the name of the ROS 2 workspace, which will be discussed in the upcoming section, and the third is the username we want to create inside Docker.
After building the image, you can create a container using the following script:
./create_container.sh ros2_gui:v0.1 master_ros2_ws ros2_devWhen executing this script, we must provide the image name we have created, the ROS 2 workspace name in the host machine, and the name of the container. The script will check if you have an NVIDIA graphics card and its driver installed on your Ubuntu OS. If installed, it will use graphics acceleration from an NVIDIA card. We are only using the docker run command inside this script but with multiple arguments for graphics acceleration, mounting volume, and ROS 2 workspace in our host OS. Creating a container like this provides the environment for running a GUI app from the terminal, and the GUI will pop up.
You will get a shell after creating a container. You can run the following command to check whether the GUI is enabled or not in the container:
robot@robot-pc:~/master_ros2_ws$ rviz2This will start RViz2, which is one of the popular ROS 2 GUI tools available. You can see RViz2 like this on the screen:

Figure 2.5: Rviz from Docker
Figure 2.5: Rviz from Docker
Congratulations! We are done creating a Docker container with GUI enabled. The rest of the script helps to start, stop, and remove containers. So, let’s see how it is used.
Start a new terminal of the running container. The argument you must provide is the container name, which is ros2_dev:
./start_container.sh ros2_devAfter starting the new terminal from the container, you will notice that it is in the path of the ROS 2 workspace we created on the host machine:
robot@robot-pc:~/master_ros2_ws$This master_ros2_ws folder is not inside the Docker container but is mounted from the local machine. If you remember, we created a ROS 2 workspace on the local machine, right? That folder is what we can access inside the Docker. We can do this by volume mounting the host OS folder during Docker container creation using the docker run command.
This is an excellent way of working with different ROS 2 distributions on the same workspace using Docker abstraction. The source code is in the host OS, but we can mount the ROS 2 workspace inside the container and build our source code with different ROS 2 distributions, such as ROS 2 Jazzy, Iron, and Humble.
We can even use an IDE such as VS Code to do remote development using a Docker container. So, in short, Docker provides an opportunity for robotics developers to quickly create ROS 2 applications and test them in any of the ROS distributions.
To stop the running container ros2_dev, we can use stop_container.sh inside the docker_gui folder. Run this script and provide the container name as an argument to stop any running container:
./stop_container.sh ros2_devWe can run remove_container.sh with the container name as the argument for removing the container:
./remove_container.sh ros2_devAfter creating the new terminal from the Docker container, you can source the following shell script, which is already present in the ROS 2 jazzy base image. This script has a command to source the ROS 2 environment:
source /ros_entrypoint.shWe have gone through some important topics of Docker that we will be using for the rest of the chapter. You can also refer to [29] [39] for more information on the ROS 2 Docker setup.
So far, we have seen how to work with a single-container application. Next, we will see how to work with multi-container applications, meaning ROS 2 nodes will work in separate containers, and these two nodes running on these different containers will communicate.
Docker Compose with ROS 2 Jazzy
Section titled “Docker Compose with ROS 2 Jazzy”Docker Compose [30] is another useful feature in Docker for robotics applications. We have worked with individual Docker containers using Docker command-line tools. What about working with multiple containers? For example, in a robotics application, we have a front-end application that is working on a JavaScript framework, a ros 2 navigation application, and a deep learning application to interact with this navigation application. In this situation, it will be better to keep all three kinds of applications in different Docker images and start communicating with each other separately from different containers. In this kind of scenario, docker-compose is a better option, as it helps to create and manage multiple containers with a single command. We can also configure the Docker network settings so that all these containers can communicate using ROS 2 DDS. The docker-compose part of the command-line tool is more like a plugin. This has already been installed in our Docker setup script.
We can write a docker-compose configuration file that contains the configuration of these multiple containers, including the Docker image, container name, and other configurations mentioned in the docker run command. Once these configuration files are written, we can start these containers with a single command.
You can find a set of Docker Compose configurations in the Chapter02 | ros2_jazzy_docker | docker_compose folder. The default name of each docker-compose configuration file is docker-compose.yml. You can find a basic docker compose file in this folder, and this is how it will look:
version: '3.8'services: talker: image: osrf/ros:jazzy-desktop-full command: ros2 run demo_nodes_cpp talker listener: image: osrf/ros:jazzy-desktop-full command: ros2 run demo_nodes_cpp listener depends_on: - talkerIf you check this configuration file, you can find the version of Docker Compose at the beginning of the file. After that, you can see the services section, which defines the containers starting as part of this compose file. In this example, talker and listener are the two containers starting with the services section. If you check this container, it uses ros-jazzy-desktop-full as the image and runs publisher and listener nodes in ROS 2 for testing. The depends_on tag says that the listener service depends on the talker. docker-compose will start the talker service first before the listener starts.
To start the docker-compose file, you can use the following command. Make sure you are inside the docker-compose code folder:
docker compose upIt will start and run all the services defined in the .yml file. By allowing you to define services, networks, and volumes in a single YAML configuration file, it simplifies the process of managing multi-container Docker applications.
You will find the output of this command as follows:

Figure 2.6: Docker Compose output
Figure 2.6: Docker Compose output
You can see both the talker and listener service talking to each other from different containers.
If you want to stop the service, you can use:
docker compose downMake sure your terminal is in the docker_compose folder.
You can also find a detailed docker-compose file from the same folder called docker-compose1.yml. This file shows more arguments that can be used in the configuration file. You can rename this file to docker-compose.yml and execute the docker compose up/down command.
Installing ROS 2 Jazzy in robots
Section titled “Installing ROS 2 Jazzy in robots”We have seen how to set up ROS 2 Jazzy in development machines, and now we can see how to set it up in robots.
In robots, we mostly use a single-board computer (SBC) or a custom-developed board with a computer module. If you examine the available popular SBCs and compute modules, you’ll find both the x86_64 and ARM64 architectures. You can install Ubuntu on these platforms and work with Docker. Two popular boards used in robots are Raspberry Pi and NVIDIA Jetson series boards.
You can find the latest Raspberry Pi boards and modules at [31]. The latest Jetson series boards and modules can be found at [32].
You can install Ubuntu 24.04 LTS 64-bit in the latest Raspberry Pi, and this is the tier 1 OS for ROS 2 Jazzy, meaning you can install ROS 2 from the binaries directly using the ROS 2 install script in the Chapter 2 code GitHub folder for this chapter. The ARM 32-bit OS is tier 3 for ROS 2 Jazzy; we must install ROS 2 by building source code. The default OS that comes with Raspberry Pi is called Raspberry Pi OS, which is a Debian-based OS that only has tier 3 support. However, you can set up Docker on Raspberry Pi OS using the Docker setup script and work on ROS 2 Jazzy in Ubuntu 24.04 (tier 1 OS) from Docker.
Here is a reference to installing Ubuntu 24.04 LTS on a Raspberry Pi board: [33].
You can also use Docker to set up ROS 2 Jazzy in Raspberry Pi using the following commands, as we have already seen:
docker pull ros:jazzy-ros-coredocker run -it --rm ros:jazzy-ros-coreThe Jetson series boards have Ubuntu by default, which is customized with NVIDIA drivers and the Jetpack SDK [34]. NVIDIA maintains its Debian packages for ROS 2. You can install their ROS 2 Jazzy on the host OS, or you can use Docker to use ROS 2 Jazzy. NVIDIA also provides jetson-containers [35] to build Docker images with other libraries. There are AI libraries, ROS, vision, and so on here, and you can choose any combination along with a script provided by NVIDIA. This is extremely useful for robotics applications.
Here is an example of using jetson-containers with multiple libraries of robotics and AI:
jetson-containers build --name=my_container pytorch transformers ros:jazzy-desktopWorking with Docker in the robot computer will be the better approach because it helps with the easier deployment of robot software without worrying about dependencies. It also helps to update the robot software easily by pulling a new image.
We have seen different methods of installing ROS 2 Jazzy in development machines and robot computers. The next section is about learning different concepts and tools in ROS 2.
Mastering ROS 2 tools and concepts
Section titled “Mastering ROS 2 tools and concepts”In this section, we will explore important concepts in ROS 2 using a hands-on approach. We must understand all these concepts before we start programming using ROS 2 Jazzy. We will see different ROS 2 tools along with understanding ROS 2 concepts. We will explain each concept using an example.
Before jumping into the concepts, we must understand why we use ROS 2 for robot programming. ROS 2 is a software framework that provides a set of libraries, tools, and capabilities for building your robotics applications. So, what is the fundamental feature of ROS 2 bringing to robot programming? It is inter-process communication, meaning the communication between the different processes in the OS. As you know, a robot can have multiple sensors, actuators, and computers. The robot sensor data has to be acquired and then processed to generate control signals to control the actuators. Generally, these operations may not be included in a single process running on the computer. The main reason is that if any operation fails, it can crash the entire process. We write multiple processes to accomplish this operation. That is where ROS 2 brings the power of inter-process communication; it can provide you with different APIs in your C++/Python and help these programs exchange data in different fashions. The data may be sent continuously to the other program, like a request-and-response interaction. This is a core feature that ROS 2 gives to robotics developers. All other features are built on top of this core feature. So, let us dive into the ROS 2 concepts.
First, we can see how to run a program in ROS 2. We are not writing a new program and running it; instead, we are trying to run an existing program, which is available in ROS 2 when you install it.
How to run ROS 2 nodes/apps in your robot
Section titled “How to run ROS 2 nodes/apps in your robot”As we already know, using ROS 2, we can create our own robotics nodes/apps for performing specific tasks in the robot. We are going to see how exactly we can run these nodes next:
- ROS 2 provides a command-line tool called
ros2. This tool helps us perform multiple operations in the ROS 2 framework. Let’s start with your ROS 2 installed machine; it can be your host OS or Docker container.
Take a terminal first, and make sure you source the ROS 2 environment. For demonstration, we are using a Docker container that was already created with the GUI in the past session. Execute this script from the docker_gui folder:
./start_container.sh ros2_dev- Source the ROS 2 environment using the following command:
source /ros_entrypoint.sh
- Execute the
ros2command in your terminal:$ ros2
If your ROS 2 environment is correctly set, you will see this output in the terminal:

Figure 2.7: ros2 command-line output
Figure 2.7: ros2 command-line output
The ros2 command is the main command in ROS 2, which comes with sub-commands, as shown in Figure 2.7. You can find sub-commands such as run, which helps to run a specific ROS 2 node. From the above list, you can identify the use of each sub-command. You can find the usage of each sub-command by simply entering it into the terminal. For example, if you enter ros2 run, you will see the sub-arguments we must pass through this terminal. The ros2 command is the main command of the ROS 2 CLI.
- To run a specific program/executable of ROS 2, use the following command:
ros2 run ros_pkg_name executable_name
Eg:
ros2 run demo_nodes_cpp talkerIn this example, demo_nodes_cpp is a ROS 2 package, and talker is the name of the C++ program executable inside this package. demo_nodes_cpp is installed along with ROS 2 Jazzy.
You may wonder what a ROS 2 package is. So, let us see what a ROS 2 package is and continue with the ros2 run command.
What is a ROS 2 package?
Section titled “What is a ROS 2 package?”A ROS 2 package is a software organization within the ROS 2 framework. It contains the necessary code and files to implement specific functionalities or features in a robotic application. Typically, a ROS 2 package comprises nodes (programs that execute computations), libraries, configuration files, launch files, and other resources such as message and service definitions.
Everything in ROS 2 is modeled inside a package. A package is simply a folder that we can create using the ros2 pkg command, and it will have files such as package.xml, CMakeLists.txt, and so on to keep the identity of the package. The information, such as the package’s name, dependencies of the package, and so on, will be included in these files.
When we install ROS 2, we will get its core packages by default. We will also get tons of ROS 2 packages from the community. These packages are easily redistributed via Git or can be added to ROS 2 official repos, and you can install their binaries.
A useful feature of ROS 2 is that it is easy to reuse the packages built by other developers in your robot. Each package is created for specific applications. For example, the demo_nodes_cpp package in ROS 2 contains ROS 2 C++ examples.
We will see more details of the structure of a ROS 2 package in the upcoming sections.
So, returning to the ros2 run command, you can see the first argument we mention is the package name and then the executable name. If you are writing a C++ program using ROS 2, it should be compiled, and we will get an executable. In this example, that executable is what we are mentioning in this command. These demo examples have already been installed with ROS 2. If you create a ROS 2 package with C++ programs, we can compile those programs and build the executable. In the next chapter, we will learn how to make a package and put C++ code inside the package.
When you run this example command, you can see the executable start running:
[INFO] [1726326377.958376860] [talker]: Publishing: 'Hello World: 1'[INFO] [1726326378.958355664] [talker]: Publishing: 'Hello World: 2'[INFO] [1726326379.958358086] [talker]: Publishing: 'Hello World: 3'Once the executable starts running, a ROS 2 node will be created.
What is a ROS node?
Section titled “What is a ROS node?”When you start a ROS 2 executable, it will run and become a process. This process is called a ROS 2 node. So, when we write a program in C++/Python using ROS 2 APIs and compile/build and run the executable, we will get a ROS 2 node. A ROS 2 node is a single process that performs some sort of computation, such as collecting sensor data, processing that data, or other operations in the robot PC or the operator PC. Nodes in ROS 2 can publish and subscribe to diverse data types with the help of underlying DDS middleware. A robotic application will have a set of ROS 2 nodes for different purposes. Each node can be launched using ros2 run; other techniques, such as ros2 launch file, allow you to launch multiple nodes in one command.
To inspect the complete details of a ROS 2 node, we can use the ros2 node command. This command gives us information about the specific node we are mentioning and a list of nodes running in the OS.
If you run the ros2 node list command in a new terminal, it will list the running nodes. In this example, the output of the command is /talker.
/talker is not our executable name; instead, the node name is what we give inside the code itself. It is not visible to us now. In the next chapter, we will demonstrate the same. You can give any name to your node, and no two nodes will have the same name. Their names should be unique!
The following command will list out details of these nodes, which include the Subscribers, Publisher, Services, and Actions:
ros2 node info /talkerHere is how we will see the output of the same:
Subscribers:Publishers: /chatter: std_msgs/msg/StringService Servers:Service Clients:Action Servers:Action Clients:In this output, there are no Subscribers, Service Servers, Clients, or Action Servers, but you can find a Publisher name, /chatter. We do not know much about ROS 2 Publisher, Subscribers, Services, and Actions yet. These terms refer to communication patterns between the different nodes. Understanding these terms will be better before returning to this point.
What is a ROS topic?
Section titled “What is a ROS topic?”We have seen the Publisher and Subscriber terms in the above command output. A publisher in a node can send a type of data, and the subscriber can also receive a type of data. The nodes publish and subscribe to several types of data through ROS topics. ROS topics are a medium of communication between different nodes. It is called a named data bus in which nodes can exchange various kinds of data. We can create any number of topics in our ROS node and send various kinds of data, such as integer, float, array, image, and so on. We can also subscribe to various kinds of data inside a ROS node. ROS topics are one communication type we use in ROS nodes. Communication with ROS topics is asynchronous, meaning the publisher can send continuous data without waiting for the receiving node. The publisher can’t even know much about who is receiving the data. We can say it is an N-to-M communication mechanism.
In the above example, the topic for publishing data is /chatter(std_msgs/msg/String). Along with the topic name, you can see the data type it is publishing: a string. In the next section, we will learn more about the different ROS data types.
We can now start a subscriber node called listener, which is subscribed to the same /chatter topic. Here is the command to run the listener node:
ros2 run demo_nodes_cpp listenerMake sure you have opened a new terminal for running this command. Also, do not confuse the executable name and node name here. The node name is defined inside the code and the executable is just a binary file. In this example, node name and executable are same, but they will not be the same in all cases.
You will get the following output with the listener node:
[INFO] [1726333039.114079927] [listener]: I heard: [Hello World: 1][INFO] [1726333040.113948341] [listener]: I heard: [Hello World: 2][INFO] [1726333041.113945517] [listener]: I heard: [Hello World: 3]After running the talker and listener nodes, you can run the following command:
ros2 node listAnd the output will be:
/listener/talkerThis output shows that, currently, two nodes are running in our system. If we try the ros2 node info /listener command, it will show the topic the /listener node is subscribed to:
Subscribers: /chatter: std_msgs/msg/StringPublishers:If we want to see how the nodes are communicating, we can use a ROS 2 GUI tool called rqt. Open a new terminal and type rqt, and you will see an empty window. Go to Plugins | Introspection | Node Graph. You can see the output like this:

Figure 2.8: rqt node graph
Figure 2.8: rqt node graph
The arrow indicates that the talker is publishing a topic named /chatter, and the /listener is subscribing to this topic. This visualization is called a node graph or ROS computation graph. After visualizing the graph, you can close the window or press Ctrl + C to close it via the terminal.
The concept of ROS computation graphs is important to understand, so let us see more on this topic.
What is a ROS computation graph?
Section titled “What is a ROS computation graph?”The ROS computation graph refers to a peer-to-peer network of ROS processes that process data together. It shows how the various system components, such as nodes, topics, services, and actions, interrelate and interchange data. The computation graph is also the least visible layer of the architecture in a ROS system. It reveals how information flows and how various parts of the software running on the robot interact.
Visualizing the computation graph will help us understand how the nodes communicate and find any problems in the communication.
Coming back to ROS 2 topics, assuming that the talker and listener are running on two terminals, take a third terminal and check the following command, which is mainly for checking the ROS 2 topics:
ros2 topic listThis command will list the topics that are currently published/subscribed to.
Here is what the output looks like:
/chatterThere is only one active topic now, which is /chatter.
Another useful command is:
ros2 topic echo /chatterThis command will subscribe to the topic /chatter and print out the data. The echo command prints messages from the specified topic. The echo can be shown as a command.
You can see the following kind of output from this:
data: 'Hello World: 1'---data: 'Hello World: 2'--We can try some commonly used sub-commands with the ros2 topic command.
The following command will print the information about the given topic. It will show how many publishers and subscribers there are for this topic, as well as the data type of this topic:
ros2 topic info /chatterThe output will look likeType: std_msgs/msg/StringPublisher count: 1Subscription count: 2We can even create a topic and publish data through this command. Here is an example of the usage:
ros2 topic pub /chatter std_msgs/msg/String "data: 'Hello, ROS 2'" -r 1This command mentions the topic name, message type, and Hello, ROS 2!, the string data to publish.
If you are running the talker node, it is already publishing the /chatter topic with string data. If you are publishing another string data type on the same topic, both data strings can be seen in the /chatter topic, and you can see both publishing if you are subscribing to this topic. If you check the terminal messages of the listener node, you will be able to find messages like this:
[INFO] [1726339920.694865075] [listener]: I heard: [Hello, ROS 2][INFO] [1726339920.853698114] [listener]: I heard: [Hello World: 1][INFO] [1726339921.694919145] [listener]: I heard: [Hello, ROS 2][INFO] [1726339921.853678698] [listener]: I heard: [Hello World: 2]We can publish different message types on the very same topic. The subscriber will only show the message type to which it is subscribed.
For example, the following commands allow you to publish a string and integer message type to the /chatter topic:
ros2 topic pub /chatter std_msgs/msg/String "data: 'Hello, ROS 2'" -r 1ros2 topic pub /chatter std_msgs/msg/Int32 "data: '2'" -r 1After running both commands in two terminals, run the listener node using the following command:
ros2 run demo_nodes_cpp listenerYou can find that only the string data is subscribed. If you create a subscriber node for Int32, it will subscribe only to the published integer data. The ros2 topic echo topic will not work because of multiple message types. Mixing different message types on the same topic is discouraged and can cause runtime errors.
You can read more about the usage of ros2 topic at [36].
Next, we can discuss ROS messages, that are used in ROS topics.
What is a ROS message?
Section titled “What is a ROS message?”In ROS 2, messages are the data structures used for communication between nodes. Messages are sent over topics (for publish/subscribe communication), through services (for request/response), or in actions (for long-running tasks). These are also ROS interfaces. A message in ROS 2 defines the type and structure of the transmitted data. These messages are defined in the .msg files, where each message combines different fields that represent specific data types (integers, strings, arrays, etc.). ROS 2 provides a set of packages dedicated to predefined message types such as std_msgs, sensor_msgs, and geometry_msgs. The std_msgs message types contain data types such as string, integer, etc. The sensor_msgs message types have a data type for images and point clouds, whereas geometry_msgs contains messages for storing poses, velocity, etc.
ROS 2 messages will have multiple fields inside them. It may not be a single string, but it can be a combination of multiple data types. The ros2 interface command is used to get the list of fields inside the ROS 2 message.
Here is an example of listing the fields inside std_msgs/msg/String:
ros2 interface show std_msgs/msg/String.Here is the output:
string dataSo, to fill the std_msgs/msg/String message with string data, you have to fill the data field inside the message.
You can find out more about ROS 2 messages from [37].
Now we can explore the concept of ROS services and actions with some examples.
What is a ROS service and how does Turtlesim work?
Section titled “What is a ROS service and how does Turtlesim work?”In ROS 2, a service is a communication model based on a call-and-response model. It involves bidirectional communication: a client sends a request to a server, and the server processes that request and sends back a response. This concept is different from ROS topics, which are unidirectional and follow a publish-subscribe model. While the underlying pattern of services is synchronous, service calls in ROS 2 can be implemented asynchronously at the node level, allowing the client to continue processing while waiting for a response.
Let’s look at an example service use case. If we want to turn something on/off in the robot, you can write a service for this, and when the client calls this service, it will execute the turn operation on/off. There are many use cases for ROS services in robots. The following figure illustrates a ROS 2 service server and client. In this diagram, two service clients interact with a ROS service server.

Figure 2.9: ROS 2 service server and client
Figure 2.9: ROS 2 service server and client
Working with examples can help us learn more about the ROS 2 service. To get hands-on with the ROS 2 service, we can use Turtlesim, a pre-installed 2D simulator in ROS 2 packages. Turtlesim is a ROS 2 node with topics, services, parameters, and actions. We can use this node to learn about all the ROS 2 concepts.
You can use the following node to start turtlesim:
ros2 run turtlesim turtlesim_nodeYou will see the following window if the command works correctly:

Figure 2.10: Turtlesim 2D simulator
Figure 2.10: Turtlesim 2D simulator
Turtlesim in ROS 2 is a graphical 2D simulator packaged with the ROS 2 desktop installation. It is mainly used for learning and experimentation with ROS 2 concepts. These tools help to understand how the ROS 2 communication concepts work.
Turtlesim is a ROS 2 node with a GUI. In this simulator, you can see a turtle at the center. The turtle is a robot; we can send velocity commands to move it. We can interact with this simulator using ROS 2 topics, services, parameters, and actions. The turtle is equipped with a pen, which can be enabled/disabled using a ROS service. The turtle will draw on the surface when it moves in the 2D plane. The color of the pen is configurable, too. It has a color sensor that will publish the color it detects from the plane, and values will be published to a topic. The drawing made by the turtle can be cleared using ROS 2 services. We can even reset the entire turtlesim simulator by calling the service.
Let us learn how a ROS 2 service works in ROS 2. Like ROS 2 topic command-line tools, there are command-line tools to analyze ROS 2 services.
We can start listing the nodes first using the following command:
ros2 node listAnd you will get the node as:
/turtlesimIf you run:
ros2 node info /turtlesimyou will get the complete details of the /turtlesim node. The output is given below:
/turtlesim Subscribers: /turtle1/cmd_vel: geometry_msgs/msg/Twist Publishers: /turtle1/color_sensor: turtlesim/msg/Color /turtle1/pose: turtlesim/msg/Pose Service Servers: /clear: std_srvs/srv/Empty /kill: turtlesim/srv/Kill /reset: std_srvs/srv/Empty /spawn: turtlesim/srv/Spawn /turtle1/set_pen: turtlesim/srv/SetPen /turtle1/teleport_absolute: turtlesim/srv/TeleportAbsolute /turtle1/teleport_relative: turtlesim/srv/TeleportRelative Service Clients: Action Servers: /turtle1/rotate_absolute: turtlesim/action/RotateAbsolute Action Clients:If you check the output in the Service Server section, you can find a set of services such as /clear, /kill, /reset, /spawn, etc. This says that Turtlesim already has these services, and you can call these services from a service client. You can also find the service data type along with the service name. The service data type will have two entries. One is for the request, and one is for the response. There can be multiple fields in the request and response. If you want to see what is inside the service type, you can use the following command.
For example, if you want to understand what fields are inside the /spawn service, you can use the following command:
ros2 interface show turtlesim/srv/SpawnYou will get the following output:
float32 xfloat32 yfloat32 thetastring name # Optional. A unique name will be created and returned if this is empty---string nameThe /spawn service creates a new turtle in the turtlesim. If you call the spawn service with the position of the new turtle and name, it will create a new turtle and return the name as a response if the service call is successful. The first part of the service definition is the request and the second is the response. These two parts are divided by --- lines.
Now, let us call this service from the command line itself.
Here is the syntax for calling a service. The ros2 service call with service name, type, and necessary data in the fields is the way to call a service from the command line. This command works as a ros 2 service client:
ros2 service call <service_name> <service_type> <arguments>Here is the example command to create a new turtle in the turtlesim. If you call the /spawn service of turtlesim with x, y, and theta values of the new turtle, it will create a new turtle in the corresponding pose. The origin is the top-left corner of the turtlesim, with the horizontal axis being X and the vertical axis being Y:
ros2 service call /spawn turtlesim/srv/Spawn "{x: 2, y: 2, theta: 0.2, name: 'turtle5'}"After executing the command, you can see the following message if the service call is okay:
waiting for service to become available...requester: making request: turtlesim.srv.Spawn_Request(x=2.0, y=2.0, theta=0.2, name='turtle5')response:turtlesim.srv.Spawn_Response(name='turtle5')After this message in the terminal, you can find a new turtle just below the turtle at the center, as shown:

Figure 2.11: Turtlesim with spawned turtle
Figure 2.11: Turtlesim with spawned turtle
You can list the services that nodes provide using the following command:
ros2 service list –tThe -t says to show the service type along with the name of the service.
You will most likely get the following output:
/clear [std_srvs/srv/Empty]/kill [turtlesim/srv/Kill]/reset [std_srvs/srv/Empty]/spawn [turtlesim/srv/Spawn]Here are a few other service call examples you can try with turtlesim.
The following command will reset the entire turtlesim. When resetting the turtlesim, all spawned turtles will be cleared, all the drawings will also be reset, and the turtle position will reset to the center:
ros2 service call /reset std_srvs/srv/Empty {}The following command will clear the drawing made by the turtle:
ros2 service call /clear std_srvs/srv/Empty {}If we want to tele-operate the turtle using a keyboard, there is a node for the same. The following command will start the node, and you can move the robot using the keyboard arrow keys:
ros2 run turtlesim turtle_teleop_keyThis node simply publishes linear and angular velocity to /turtle1/cmd_vel, and the message type is geometry_msgs/msg/Twist. This topic is subscribing to the turtlesim and moving the robot based on the velocity commands. So, in this case, /teleop_turtle is the publisher node and turtlesim is the subscriber node.
Here is one source you can refer to read more about the ROS 2 service: [38].
In this section, we explored how to work with ROS 2 services using Turtlesim and ROS 2 command-line tools, demonstrating the synchronous communication between nodes and various service operations such as spawning, resetting, and controlling the turtle.
Summary
Section titled “Summary”This chapter provided a practical guide to setting up and working with ROS 2, focusing on installing ROS 2 Jazzy on various platforms such as Ubuntu, Windows, and macOS, and using virtualization tools such as Docker and VirtualBox. It introduced ROS 2 basics, including key concepts such as nodes, topics, packages, and messages, while using tools such as Turtlesim to demonstrate inter-process communication. The chapter also covered using ROS 2 client libraries for application development in multiple programming languages and emphasized setting up a development environment, building robot software, and understanding ROS 2 concepts through hands-on examples.
In the next chapter, we will continue with ROS 2 actions and ROS 2 package creation, and start with ROS 2 programming.
References
Section titled “References”- [1] https://ubuntu.com/download/desktop
- [2] https://ubuntuhandbook.org/index.php/2024/04/install-ubuntu-24-04-desktop/
- [3] https://mac.getutm.app/
- [4] https://www.virtualbox.org/wiki/Downloads
- [5] https://www.vmware.com/products/desktop-hypervisor
- [6] https://itslinuxguide.com/install-ubuntu-virtualbox/
- [7] https://youtu.be/SgfrHKg81Qc
- [8] https://mac.getutm.app/
- [9] https://www.linuxbuzz.com/how-to-install-ubuntu-on-wsl/
- [10] https://www.docker.com/
- [11] https://hub.docker.com/
- [12] https://raspberrytips.com/install-ubuntu-desktop-raspberry-pi/
- [13] https://ubuntu.com/download/nvidia-jetson
- [14] https://docs.ros.org/en/jazzy/Installation.html
- [15] https://gnupg.org/
- [16] https://launchpad.net/ubuntu/+ppas
- [17] https://ubuntu.com/desktop/wsl
- [18] https://docs.ros.org/en/jazzy/Installation/Windows-Install-Binary.html
- [19] https://mac.getutm.app/
- [20] https://docs.ros.org/en/jazzy/Installation/Alternatives/macOS-Development-Setup.html
- [21] https://youtu.be/qjfBP4UYx9c?si
- [22] https://ubuntuasahi.org/
- [23] https://www.docker.com/
- [24] https://docs.docker.com/engine/install/ubuntu/
- [25] https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/index.html
- [26] https://hub.docker.com/
- [27] https://hub.docker.com/r/osrf/ros/tags
- [28] https://docs.docker.com/get-started/docker_cheatsheet.pdf
- [29] https://roboticseabass.com/2023/07/09/updated-guide-docker-and-ros2/
- [30] https://docs.docker.com/reference/cli/docker/compose/
- [31] https://www.raspberrypi.com/products/
- [32] https://developer.nvidia.com/buy-jetson
- [33] https://ubuntu.com/download/raspberry-pi
- [34] https://developer.nvidia.com/embedded/jetpack
- [35] https://github.com/dusty-nv/jetson-containers
- [36] https://roboticsbackend.com/ros2-topic-cmd-line-tool-debug-ros2-topics-from-the-terminal/
- [37] https://ros2-tutorial.readthedocs.io/en/latest/messages.html
- [38] https://docs.ros.org/en/jazzy/Tutorials/Beginner-CLI-Tools/Understanding-ROS2-Services/Understanding-ROS2-Services.html
- [39] https://github.com/2b-t/docker-for-robotics