Making a local Ubuntu/Debian repository mirror

Using debmirror the entire contents of the official package repositories can be copied locally.

sudo apt-get install debmirror
mkdir /var/ubuntu-mirror
gpg --keyring /usr/share/keyrings/ubuntu-archive-keyring.gpg --export | gpg --no-default-keyring --keyring /var/ubuntu-mirror/trustedkeys.gpg --import
GNUPGHOME=/var/ubuntu-mirror debmirror \                                                       
        -a amd64 \
        --no-source \
        -s main,restricted,universe,multiverse \
        -h ro.archive.ubuntu.com \
        -d bionic,bionic-security,bionic-updates,bionic-backports,focal,focal-security,focal-updates,focal-backports \
        -r /ubuntu \
        --progress \
        --method=http \
        /var/ubuntu-mirror/
sudo apt-get install nginx

Add the lines marked with + (without adding the + sign at the start of each line).

 server {
 	listen 80 default_server;
 	listen [::]:80 default_server;
 
 # ...
 # ... 
+	location ^~ /mirror {
+		alias /var/ubuntu-mirror;
+		autoindex on;
+		try_files $uri $uri/ =404;
+	}
 # ...
 # ...
 
 }
sudo systemctl restart nginx
deb http://192.168.111.118/mirror focal main restricted universe multiverse
deb http://192.168.111.118/mirror focal-updates main restricted universe multiverse
deb http://192.168.111.118/mirror focal-backports main restricted universe multiverse
deb http://security.ubuntu.com/ubuntu focal-security main restricted universe multiverse

Additionally, you can use an ansible script to switch to the mirror:

  - name: remove support for i386
    become: true
    shell: dpkg --remove-architecture i386

  - name: replace apt mirror on ubuntu
    become: true
    copy:
      dest: /etc/apt/sources.list
      content: |
               deb http://192.168.111.118/mirror focal main restricted universe multiverse
               deb http://192.168.111.118/mirror focal-updates main restricted universe multiverse
               deb http://192.168.111.118/mirror focal-backports main restricted universe multiverse
               deb http://security.ubuntu.com/ubuntu focal-security main restricted universe multiverse

  - name: update apt cache on ubuntu
    become: true
    apt:
      update_cache: yes