Set Memory Usage for a Podman Container
Table of Contents
How to limit memory resource for a Podman container#
This is a simple and quick script to set amount of memory for a Podman container.
This can be helpful if you are running alot of containers via Distrobox.
Take a look at the script below and feel free to modify it as you like:
#!/usr/bin/env bash
# Capture the output from the 'podman ps' command
podman_output="$(podman ps --all --no-trunc --format "{{.Names}} {{.ID}} {{.Labels}}" | grep "manager:distrobox" | cut -d " " -f1,2 | column -t)"
# Define an associative array to store the tokens
declare -A tokens
# Parse and store the tokens
while read -r name token; do
tokens["$name"]="$token"
done <<< "$podman_output"
# Prompt the user for RAM amount and container name
read -p "Enter RAM amount (e.g., 4G): " ram
read -p "Enter the container name: " container_name
# Check if the user-specified container name is in the tokens array
if [ -n "${tokens[$container_name]}" ]; then
token="${tokens[$container_name]}"
# Use the user input to replace the token and RAM in the systemctl command
systemctl_command="systemctl --user set-property libpod-$token.scope MemoryMax=$ram && systemctl --user status libpod-$token.scope | grep 'Memory: '"
# Execute the systemctl command
echo "Executing: $systemctl_command"
eval "$systemctl_command"
else
echo "Container name '$container_name' not found in the captured data."
fi
# Spacer
echo ""
# Store the running container names in a variable
running_containers=$(podman ps --format '{{.Names}}' --filter status=running)
# Get the container details including tokens
container_details=$(podman ps --all --no-trunc --format "{{.Names}} {{.ID}} {{.Labels}}" | grep "mana
ger:distrobox" | cut -d " " -f1,2)
# Loop through each line of the container details
while read -r line; do
container_name=$(echo $line | awk '{print $1}')
container_token=$(echo $line | awk '{print $2}')
if [[ $running_containers == *"$container_name"* ]]; then
echo "Container: $container_name"
systemctl --user status libpod-$container_token.scope | grep 'Memory: '
echo
fi
done <<< "$container_details"
Read other posts