Skip to content

Instantly share code, notes, and snippets.

@degrammer
Created April 26, 2024 21:41
Show Gist options
  • Save degrammer/b3b32d8e6b4350ae5aa7e290883c542a to your computer and use it in GitHub Desktop.
Save degrammer/b3b32d8e6b4350ae5aa7e290883c542a to your computer and use it in GitHub Desktop.

File name: shebang.md

Session: 01HWE53MJN9GNBSRK5NY7V0JAX


▢️ Generated by Runme

Share your own terminal sessions, it's free and open source. Click here to learn more.

runme
id version document session
01HF7B0KJQ8625WYMCRVJADMQF
v3
relativePath
shebang.md
id updated
01HWE53MJN9GNBSRK5NY7V0JAX
2024-04-26 16:39:57 -0500

Runme Language Support

By default Runme can run everything that is also installed on your machine.

Shebang is a versatile tool designed to execute scripts written in various scripting languages including Shell, Perl, Python, Ruby, Node.js, and more. Runme integrates Shebang to enable users to run the script of their choice directly from the Markdown file in their preferred programming language.

Let's learn how to use multiple programming languages to interact with your containers!

In this example we will write a simple script in different programming languages that lists your running containers.

πŸ’‘ Before starting, ensure you have the following installed in your machine:

  • Docker 🐳
  • Python 🐍 (for Python example)
  • Ruby πŸ’Ž (for Ruby example)
  • Node.js 🍦 (for Node.js example)

Ensure docker is up and running

Run the following check, just to ensure you have Docker up and running

#!/bin/bash

# Check if Docker is installed
if ! command -v docker &> /dev/null
then
    echo "Docker is not installed."
    exit
fi

# Check if Docker daemon is running
if ! docker info &> /dev/null
then
    echo "Docker daemon is not running. ❌"
    exit
fi

echo "Docker is installed and running. βœ…"


# Ran on 2024-04-26 16:39:32-05:00 for 1.73s exited with 0
Docker is installed and running. βœ…

Ensure you have a list one container to list, if you don't have one, you can start a nginx container by running the following command:

docker rm -f my_runme_demo_container
docker run -d --name my_runme_demo_container -p 8080:80 nginx

# Ran on 2024-04-26 16:39:35-05:00 for 1.457s exited with 0
my_runme_demo_container
305df64b31161f04b51cc6e9b13bab919759acdb73ba01a7f974cf94c8977f6f

Python 🐍

Requirements

  • Ensure you have python installed
  • Create a virtual env
  • Install the docker and prettytable packages
python3 -m venv .venv
source .venv/bin/activate
pip3 install docker prettytable

# Ran on 2024-04-26 16:39:38-05:00 for 3.679s exited with 0
Requirement already satisfied: docker in ./.venv/lib/python3.12/site-packages (7.0.0)
Requirement already satisfied: prettytable in ./.venv/lib/python3.12/site-packages (3.10.0)
Requirement already satisfied: packaging>=14.0 in ./.venv/lib/python3.12/site-packages (from docker) (24.0)
Requirement already satisfied: requests>=2.26.0 in ./.venv/lib/python3.12/site-packages (from docker) (2.31.0)
Requirement already satisfied: urllib3>=1.26.0 in ./.venv/lib/python3.12/site-packages (from docker) (2.2.1)
Requirement already satisfied: wcwidth in ./.venv/lib/python3.12/site-packages (from prettytable) (0.2.13)
Requirement already satisfied: charset-normalizer<4,>=2 in ./.venv/lib/python3.12/site-packages (from requests>=2.26.0->docker) (3.3.2)
Requirement already satisfied: idna<4,>=2.5 in ./.venv/lib/python3.12/site-packages (from requests>=2.26.0->docker) (3.7)
Requirement already satisfied: certifi>=2017.4.17 in ./.venv/lib/python3.12/site-packages (from requests>=2.26.0->docker) (2024.2.2)

[notice] A new release of pip is available: 23.2.1 -> 24.0
[notice] To update, run: pip install --upgrade pip

Now you have all the requirements ready, run the following Python script to get a list of running containers in a nice table format.

import docker
from prettytable import PrettyTable

def list_running_containers():
    client = docker.from_env()
    containers = client.containers.list()

    if containers:
        table = PrettyTable(["Container ID", "Name", "Image", "Status"])
        for container in containers:
            table.add_row([container.id[:12], container.name, container.attrs['Config']['Image'], container.status])
        print("Running containers:")
        print(table)
    else:
        print("No running containers found.")

if __name__ == "__main__":
    list_running_containers()

# Ran on 2024-04-26 16:39:39-05:00 for 492ms exited with 0
Running containers:
+--------------+-------------------------+-------+---------+
| Container ID |           Name          | Image |  Status |
+--------------+-------------------------+-------+---------+
| 305df64b3116 | my_runme_demo_container | nginx | running |
+--------------+-------------------------+-------+---------+

Ruby πŸ’Ž

Requirements

  • Ensure you have Ruby installed
  • Install docker-api and terminal-table gems

Ensure you have ruby installed at least running version >= 2.7.0 (required to have this demo working). You can run the following command to check your ruby version:

ruby -v

Install required gems

gem install docker-api terminal-table

# Ran on 2024-04-26 16:34:41-05:00 for 32.168s exited with 0
Successfully installed docker-api-2.2.0
Parsing documentation for docker-api-2.2.0
Done installing documentation for docker-api after 0 seconds
Successfully installed terminal-table-3.0.2
Parsing documentation for terminal-table-3.0.2
Done installing documentation for terminal-table after 0 seconds
2 gems installed
Now you have all the requirements ready, run the following Ruby script to get a list of running containers in a nice table format.
require 'docker-api'
require 'terminal-table'

def list_running_containers
  Docker.url = 'unix:///var/run/docker.sock'
  containers = Docker::Container.all(:all => false)

  if containers.any?
    table = Terminal::Table.new :headings => ['Container ID', 'Name', 'Image', 'Status'] do |t|
      containers.each do |container|
        t << [container.id[0..11], container.info['Names'][0], container.info['Image'], container.info['State']]
      end
    end
    puts "Running containers:"
    puts table
  else
    puts "No running containers found."
  end
end

list_running_containers


# Ran on 2024-04-26 16:39:46-05:00 for 428ms exited with 0
Running containers:
+--------------+--------------------------+-------+---------+
| Container ID | Name                     | Image | Status  |
+--------------+--------------------------+-------+---------+
| 305df64b3116 | /my_runme_demo_container | nginx | running |
+--------------+--------------------------+-------+---------+

Node.js 🍦

Install required node packages

npm i cli-table3 dockerode

# Ran on 2024-04-26 16:39:51-05:00 for 2.089s exited with 0
(##################) β ‡ reify:@esbuild/aix-ppc64: timing reifyNode:node_modules/@(##################) β Έ reify:@esbuild/aix-ppc64: timing reifyNode:node_modules/@(##################) β Ό reify:@esbuild/aix-ppc64: timing reifyNode:node_modules/@(##################) β Ό reify:@esbuild/aix-ppc64: timing reifyNode:node_modules/@(##################) β Ό reify:@esbuild/aix-ppc64: timing reifyNode:node_modules/@(##################) β Ό reify:@esbuild/aix-ppc64: timing reifyNode:node_modules/@(##################) β Ό reify:@esbuild/aix-ppc64: timing reifyNode:node_modules/@(##################) β Ό reify:@esbuild/aix-ppc64: timing reifyNode:node_modules/@(##################) β Ό reify:@esbuild/aix-ppc64: timing reifyNode:node_modules/@(##################) ⠏ reify:@esbuild/aix-ppc64: timing reifyNode:node_modules/@

up to date, audited 1999 packages in 2s

277 packages are looking for funding
  run `npm fund` for details

5 vulnerabilities (2 moderate, 3 high)

Some issues need review, and may require choosing
a different dependency.

Run `npm audit` for details.
 *  Program exited with code 0.

Now you have all the requirements ready, run the following Node.js script to get a list of running containers in a nice table format.

const Docker = require('dockerode');
const Table = require('cli-table3');

// Initialize Docker API
const docker = new Docker({ socketPath: '/var/run/docker.sock' });

function listRunningContainers() {
  docker.listContainers({ all: false }, (err, containers) => {
    if (err) {
      console.error('Error fetching containers:', err);
      return;
    }

    if (containers.length > 0) {
      const table = new Table({
        head: ['Container ID', 'Name', 'Image', 'Status']
      });

      containers.forEach(containerInfo => {
        const containerId = containerInfo.Id.substr(0, 12);
        const containerName = containerInfo.Names[0];
        const containerImage = containerInfo.Image;
        const containerStatus = containerInfo.State;

        table.push([containerId, containerName, containerImage, containerStatus]);
      });

      console.log('Running containers:');
      console.log(table.toString());
    } else {
      console.log('No running containers found.');
    }
  });
}

listRunningContainers();


Running containers:
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Container ID β”‚ Name                     β”‚ Image β”‚ Status  β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ 305df64b3116 β”‚ /my_runme_demo_container β”‚ nginx β”‚ running β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment