How to Install OSRM on Ubuntu 22.04 – Open Source Routing Machine

OSRM (Open Source Routing Machine) is a super fast routing engine for OpenStreetMap (OSM) road networks. In previous tutorials, we explained the process of setting up a self-hosted OpenStreetMap tile server and how to add address lookup functionality to your map with Nominatim. This tutorial is going to show you how to add navigation functionality to your OpenStreetMap with OSRM, which provides car routing, bike routing, and walk routing.

Install OSRM on Ubuntu 20.04

Prerequisites

To follow this tutorial, you should have an OSM tile server up and running. If not, please follow the tutorial below to set up your own OSM tile server.

You should also have access to a geocoding service like Nominatim for address lookup.

Once the requirements are met, follow the instructions below to set up OSRM server.

Step 1: Build OSRM From Source

Install dependency packages.

sudo apt update

sudo apt install build-essential git cmake pkg-config doxygen libboost-all-dev libtbb-dev lua5.2 liblua5.2-dev libluabind-dev libstxxl-dev libstxxl1v5 libxml2 libxml2-dev libosmpbf-dev libbz2-dev libzip-dev libprotobuf-dev

Create the osrm user. (No need to create a password for this user.)

sudo useradd -d /srv/osrm -s /bin/bash -m osrm

Grant permissions to your own user account. Replace username with your real Linux username.

sudo apt install acl

sudo setfacl -R -m u:username:rwx /srv/osrm/

Change to the /srv/osrm/ directory.

cd /srv/osrm/

Download the OSRM source code from its Github repository.

git clone https://github.com/Project-OSRM/osrm-backend.git

Create the build directory.

mkdir build

Change to this directory and configure the build environment.

cd build

cmake /srv/osrm/osrm-backend/

Compile the source code. (If you see some TBB warning: deprecated message, you can ignore them.)

make

build OSRM from source ubuntu 20.04

Install the binaries.

sudo make install

The following binaries will be installed.

  • /usr/local/bin/osrm-extract:
  • /usr/local/bin/osrm-partition:
  • /usr/local/bin/osrm-customize:
  • /usr/local/bin/osrm-contract:
  • /usr/local/bin/osrm-datastore:
  • /usr/local/bin/osrm-routed:

Step 2: Install GNU Screen

In the next step, we will need to extract road networks from OpenStreetMap, which can take a long time. Your computer might be disconnected from the Internet, so it’s recommended to use the GNU Screen utility to keep your session alive. Install screen on the Ubuntu 22.04 server:

sudo apt install screen

Then start screen:

screen

Upon the first launch, you will see an introduction text, simply press Enter to end. Then you will be able to run commands as usual.

Step 3: Generate OSRM Routing Data

Now we need to download the OpenStreetMap data and make it usable for routing. Run the following command to download the map data of the whole planet (56G) in PBF (ProtoBufBinary) format.

wget -c http://planet.openstreetmap.org/pbf/planet-latest.osm.pbf -P /srv/osrm/osrm-backend

If you want a map of an individual country/state/province/city, go to http://download.geofabrik.de. For example, download the map data of Great Britain (1.7G) with the following command.

wget -c http://download.geofabrik.de/europe/britain-and-ireland-latest.osm.pbf -P /srv/osrm/osrm-backend

BBBike.org also provides extracts of more than 200 cities and regions worldwide in different formats.

Make sure you are in the /srv/osrm/osrm-backend/ directory.

cd /srv/osrm/osrm-backend/

Extract a graph out of the OpenStreetMap data.

osrm-extract britain-and-ireland-latest.osm.pbf --threads=10

By default, it will use the car.lua profile.

Generate-OSRM-Routing-Data-ubuntu-22.04

Now you probably don’t need to do other things on your server. Since you are using Screen, you can press Ctrl+A, release those keys, and then press D key to detach from the current Screen session. You will see a message like below.

[detached from 32113.pts-1.focal]

This tells me that the previous Screen session ID is 32113. You can log out from the SSH session and even shut down your computer. Don’t worry, the osrm-extract process is still running. When you need to come back and check the progress, SSH into your server and run the following command to get the previous Screen Session ID.

screen -ls

Sample output:

There is a screen on:
	32113.pts-1.focal	(05/19/2020 03:45:29 PM)	(Detached)
1 Socket in /run/screen/S-linuxbabe.

Then you can re-attach to the previous Screen session.

screen -r 32113

This process is resource-intensive. It uses 9GB RAM on my server and the CPU load goes up to 6. I use the Britain and Ireland map. If you use the whole planet map, RAM usage can go up to 120GB, so you probably want to create a swap file to increase the total memory.

Once it’s finished, there will be a file with the same filename but with the .osrm extension. Run the following command to partition this graph recursively into cells.

osrm-partition britain-and-ireland-latest.osrm

osrm-partition ubuntu 22.04

Customize the cells by calculating routing weights for all cells.

osrm-customize britain-and-ireland-latest.osrm

osrm-customize ubuntu 22.04

Now you can start the routing engine.

osrm-routed --algorithm=MLD britain-and-ireland-latest.osrm

osrm-routed ubuntu 22.04

As you can see, it listens on TCP port 5000.

Step 4: Creating a systemd service

We can manually run the OSRM routing engine with osrm-routed --algorithm=MLD britain-and-ireland-latest.osrm, but it’s more convenient to run osrm-routed as a systemd service in the background.

Press Ctrl+C to stop the current osrm-routed process and create a systemd service unit file for osrm-routed with the following command.

sudo nano /etc/systemd/system/osrm-routed.service

Put the following lines into the file.

[Unit]
Description=Open Source Routing Machine
Wants=network-online.target
After=network.target network-online.target

[Service]
ExecStart=/usr/local/bin/osrm-routed --algorithm=MLD /srv/osrm/osrm-backend/britain-and-ireland-latest.osrm
User=osrm
Group=osrm
Restart=always
RestartSec=5s

[Install]
WantedBy=multi-user.target

Save and close the file. Change the ownership of the /srv/osrm/osrm-backend/ directory.

sudo chown osrm:osrm /srv/osrm/osrm-backend/ -R

Now we can start and enable the osrm-routed systemd service.

sudo systemctl start osrm-routed

sudo systemctl enable osrm-routed

Check status.

systemctl status osrm-routed

osrm-routed-systemd-service-ubuntu-22.04

If the osrm-routed service isn’t active (running), you can run the following command to see what’s wrong.

sudo journalctl -eu osrm-routed

Step 5: Set Up Reverse Proxy

We can configure Apache or Nginx web server as a reverse proxy for the osrm-routed service, so we will be able to use a domain name to access the routing service and also enable HTTPS encryption.

Apache

Install Apache web server.

sudo apt install apache2

To use Apache as a reverse proxy, we need to enable the proxy, proxy_http and rewrite module.

sudo a2enmod proxy proxy_http rewrite

Then create a virtual host file for OSRM.

sudo nano /etc/apache2/sites-available/osrm.conf

Add the following texts into the file. Replace osrm.your-domain.com with your actual domain name and don’t forget to create DNS A record for it.

<VirtualHost *:80>
    ServerName osrm.your-domain.com

    ProxyPass / http://127.0.0.1:5000/
    ProxyPassReverse / http://127.0.0.1:5000/
</VirtualHost>

Save and close the file. Then enable this virtual host.

sudo a2ensite osrm.conf

Reload Apache for the changes to take effect.

sudo systemctl reload apache2

Now you can remotely access OSRM by entering the domain name (osrm.your-domain.com ) in browser address bar.

Nginx

Nginx is a very popular web server and reverse proxy. If you prefer to use Nginx, run the following command to install it.

sudo apt install nginx

Then create a server block file for OSRM.

sudo nano /etc/nginx/conf.d/osrm.conf

Add the following content to this file. Replace osrm.your-domain.com with your actual domain name and don’t forget to create DNS A record for it.

server {
      listen 80;
      listen [::]:80;
      server_name osrm.your-domain.com;

      access_log /var/log/nginx/osrm.access;
      error_log /var/log/nginx/osrm.error;

      location / {
          proxy_pass http://127.0.0.1:5000;
          proxy_set_header Host $host;
          proxy_set_header X-Real-IP $remote_addr;

          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_set_header X-Forwarded-Proto $scheme;
          proxy_set_header X-Forwarded-Protocol $scheme;
          proxy_set_header X-Forwarded-Host $http_host;
      }
}

Save and close this file. Then test Nginx configuration.

sudo nginx -t

If the test is successful, reload Nginx for the change to take effect.

sudo systemctl reload nginx

Step 6: Enable HTTPS

We can enable HTTPS by installing a free TLS certificate issued from Let’s Encrypt. In the OSM tile server setup tutorial, we have already installed the Let’s Encrypt client (certbot) from the Snap store. So we just need to run the following command to obtain and install TLS certificate.

Apache

sudo /snap/bin/certbot --apache --agree-tos --redirect --hsts --staple-ocsp --email [email protected] -d osrm.your-domain.com

Nginx

sudo /snap/bin/certbot --nginx --agree-tos --redirect --hsts --staple-ocsp --email [email protected] -d osrm.your-domain.com

Where:

  • --apache: Use the Apache plugin.
  • --nginx: Use the Nginx plugin.
  • --agree-tos: Agree to terms of service.
  • --redirect: Force HTTPS by 301 redirects.
  • --hsts: Add the Strict-Transport-Security header to every HTTP response. Forcing browser to always use TLS for the domain. Defends against SSL/TLS Stripping.
  • --staple-ocsp: Enables OCSP Stapling. A valid OCSP response is stapled to the certificate that the server offers during TLS.

The certificate should now be obtained and automatically installed. And you will be able to access Webmin web interface over a secure HTTPS connection.

osrm https certbot ubuntu 20.04

Step 7: Integrate OSRM with a Slippy Map

I assume your slippy map is displayed using the Leaflet JavaScript library, and you have added Nominatim geocoding service to your slippy map.

To integrate OSRM with a slippy map, we can use a plugin called Leaflet Routing Machine. First, include the Leaflet routing machine JavaScript and CSS file to your slippy map. Note that they should be placed after the main Leaflet JavaScript and the Leaflet Control Geocoder JavaScript.

<html>
  <head>
     ....
     ....
     <link rel="stylesheet" href="https://unpkg.com/leaflet-routing-machine@latest/dist/leaflet-routing-machine.css" />
     <script src="https://unpkg.com/leaflet-routing-machine@latest/dist/leaflet-routing-machine.js"></script>
 </head>
 <body>
 ....
 ....
 </body>
</html>

Next, add the following lines to the <script>...</script> snippet in the HTML body.

     L.Routing.control({
         serviceUrl: 'https://osrm.your-domain.com/route/v1',
         geocoder: L.Control.Geocoder.nominatim({serviceUrl:'https://tile.your-domain.com/nominatim/'}),
         routeWhileDragging: true
       }).addTo(map);

Like this:

<html>
  <head>
     ....
     ....
     <link rel="stylesheet" href="https://unpkg.com/leaflet-routing-machine@latest/dist/leaflet-routing-machine.css" />
     <script src="https://unpkg.com/leaflet-routing-machine@latest/dist/leaflet-routing-machine.js"></script>
 </head>
 <body>
   <div id="map"></div>
     <script>
     ....
     ....


     L.Routing.control({
         serviceUrl: 'https://osrm.your-domain.com/route/v1',
         geocoder: L.Control.Geocoder.nominatim({serviceUrl:'https://tile.your-domain.com/nominatim/'}),
         routeWhileDragging: true
       }).addTo(map);

    </script>

  </body> 
</html>

Save and close the file. Then reload the map in your web browser, you should see a control panel on the upper-right corner, where you can enter the starting address and destination address.

Install OSRM on Ubuntu 20.04

You can drag the waypoints on the map and OSRM will automatically recalculate the route.

Wrapping Up

I hope this tutorial helped you set up OSRM server on Ubuntu 22.04. As always, if you found this post useful, then subscribe to our free newsletter to get more tips and tricks. Take care 🙂

Rate this tutorial
[Total: 2 Average: 4.5]

4 Responses to “How to Install OSRM on Ubuntu 22.04 – Open Source Routing Machine

  • rosario
    1 year ago

    HI. Your article is very interesting and clear. At the beginning you say that you need to install an OSM server. How does OSRM interact with OSM server? And does it cost change if I have OSM in a docker?

  • Thanks for this informative articles! Really appreciate much.
    Just wondering which version of osrm-backend was used here.
    Version 5.27.1 seems like throwing me errors when i want to install OSRM from source

    • david knibb
      9 months ago

      I’ve got my osm server on a Debian 11 machine – not Ubuntu

      I would like to install OSRM. Would following one of the Ubuntu programmes work equally as well on Ubuntu . ? As far as I can see you haven’t published a Debian article ??
      Thanks
      David

Leave a Comment

  • Comments with links are moderated by admin before published.
  • Your email address will not be published.
  • Use <pre> ... </pre> HTML tag to quote the output from your terminal/console.
  • Please use the community (https://community.linuxbabe.com) for questions unrelated to this article.
  • I don't have time to answer every question. Making a donation would incentivize me to spend more time answering questions.

The maximum upload file size: 2 MB. You can upload: image. Links to YouTube, Facebook, Twitter and other services inserted in the comment text will be automatically embedded. Drop file here