How to install docker and docker-compose on Ubuntu 18.04 or 20.04

docker

Table of Contents

Install docker-compose on your VM instance by creating a file as follows:

nano install_docker.sh

Inside the file copy and paste the following code:

#!/bin/bash

# Exit script if any command fails
set -e

# Install Docker
echo "Updating package information..."
sudo apt update -y
echo "Installing prerequisites..."
sudo apt -y install apt-transport-https ca-certificates curl software-properties-common
echo "Adding Docker's official GPG key..."
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
echo "Adding Docker repository..."
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu focal stable"
echo "Installing Docker..."
sudo apt -y install docker-ce 

# Manage Docker as a non-root user
echo "Adding the current user to the Docker group..."
sudo usermod -aG docker ${USER}
su - ${USER}

# Install Docker Compose
echo "Installing Docker Compose..."
sudo apt install docker-compose-plugin

# Print Docker and Docker Compose versions to verify installation
echo "Docker version:"
sudo docker --version
echo "Docker Compose version:"
docker compose --version

echo "Installation complete. Please log out and back in for group changes to take effect, or start a new shell session."

Finally run the file using the following command:

chmod +x install_docker.sh
./install_docker.sh