DEV Community

Cover image for How to Safely Run Claude Code on Ubuntu 24.04: The SRE Playbook
Jakson Tate
Jakson Tate

Posted on • Originally published at servermo.com

How to Safely Run Claude Code on Ubuntu 24.04: The SRE Playbook

Claude Code is an extraordinary terminal agent, but a massive industry misconception assumes it operates entirely free from commercial fees or acts like a fixed-price monthly subscription.

In reality, the agent utilizes external APIs to process intelligence dynamically. Because it operates autonomously, it repeatedly reads your entire project repository, continuously consuming millions of tokens based on repository size.

Before migrating your workspace to a ServerMO Dedicated Server for its massive compilation speed, you must address the financial risk. A rogue agent analyzing an unoptimized directory can exhaust hundreds of dollars rapidly. You must log into your developer console and establish hard billing limits to prevent catastrophic cloud shock invoices.


Phase 1: True API Economics and DBus-Safe Host Persistency

To build a secure remote environment, we utilize Rootless Podman, entirely abandoning dangerous root-level daemons. However, Linux kernels terminate rootless background services the exact moment you disconnect your SSH session.

You must enable user linger to ensure your artificial intelligence agent remains active continuously. Finally, you must avoid the DBus session trap by initiating a pure SSH connection.

# Establish a strictly isolated developer environment
sudo adduser --gecos "" ai_developer

# Grant the user persistent execution rights preventing SSH disconnect crashes
sudo loginctl enable-linger ai_developer

# Install Podman for daemonless rootless container execution
sudo apt-get update && sudo apt-get install -y podman

# DO NOT switch users locally (e.g., su ai_developer). This destroys the DBus session variables.
# Log out of your current session completely.

# Reconnect directly as the developer to initialize the DBus session perfectly
ssh ai_developer@your_server_ip
mkdir -p ~/claude_podman && cd ~/claude_podman
Enter fullscreen mode Exit fullscreen mode

Phase 2: The Omni Toolchain Containerfile

Executing background containers without standard terminal input causes the shell to exit instantly, generating a dead zombie container. We utilize an infinite sleep loop to maintain continuous execution.

Crucially, we are building a dedicated development box which acts as an omni-toolchain container. We must embed all Model Context Protocol (MCP) dependencies, like the Python uv package manager, directly into the build eliminating "command not found" crashes seamlessly.

Create your Containerfile:

FROM docker.io/ubuntu:24.04

# Install prerequisite tools and certificates securely
RUN apt-get update && apt-get install -y git curl sudo ca-certificates

# Establish NodeSource repository for modern environment compatibility
RUN curl -fsSL [https://deb.nodesource.com/setup_22.x](https://deb.nodesource.com/setup_22.x) | bash - && \
    apt-get install -y nodejs

# Create Developer User directly
RUN useradd -m -s /bin/bash aideveloper

# Switch to the synchronized account mapping user-scoped NPM paths
USER aideveloper
RUN mkdir -p /home/aideveloper/.npm_global
ENV NPM_CONFIG_PREFIX=/home/aideveloper/.npm_global
ENV PATH="/home/aideveloper/.npm_global/bin:${PATH}"

# Embed the Python uv package manager permanently preventing MCP server crashes
RUN curl -LsSf [https://astral.sh/uv/install.sh](https://astral.sh/uv/install.sh) | sh
ENV PATH="/home/aideveloper/.local/bin:${PATH}"

# Install the agent securely preventing legacy permission crashes
RUN npm install -g @anthropic-ai/claude-code

WORKDIR /workspace

# Maintain continuous execution preventing zombie container termination
CMD ["sleep", "infinity"]
Enter fullscreen mode Exit fullscreen mode

Compile the image safely within your standard user permissions:

podman build -t claude-secure-agent ~/claude_podman/
Enter fullscreen mode Exit fullscreen mode

Phase 3: Pristine Quadlet Systemd Integration

Enterprise SRE teams utilize Quadlet to define containers as native Linux services. This automates volume mapping effortlessly resolving all complex permission issues.

However, many legacy guides hallucinate volume mount security flags intended for SELinux environments. Ubuntu utilizes AppArmor, making those specific security anomalies completely irrelevant. Our configuration remains pristine and mathematically accurate for Ubuntu deployments.

# Create the required Quadlet configuration directory
mkdir -p ~/.config/containers/systemd/

# Pre-create host directories avoiding permission drift
mkdir -p ~/my_project ~/.anthropic ~/.config/claude-code
Enter fullscreen mode Exit fullscreen mode

Define the native container service file (~/.config/containers/systemd/claude-agent.container):

[Container]
Image=localhost/claude-secure-agent:latest

# Pure volume mapping executed safely for AppArmor
Volume=%h/my_project:/workspace
Volume=%h/.anthropic:/home/aideveloper/.anthropic
Volume=%h/.config/claude-code:/home/aideveloper/.config/claude-code
Terminal=true

[Install]
WantedBy=default.target
Enter fullscreen mode Exit fullscreen mode

Phase 4: Zero-Amnesia Headless Authorization

With the Quadlet file positioned, you simply instruct the system daemon to recognize your new service. We then initiate the container and execute the headless authentication sequence across your secure shell connection.

# Reload the system daemon to recognize the Quadlet configuration flawlessly
systemctl --user daemon-reload

# Start the artificial intelligence container gracefully in the background
systemctl --user start claude-agent

# Enter the isolated environment securely to authenticate the agent
podman exec -it claude-agent claude login
Enter fullscreen mode Exit fullscreen mode

The command-line interface will output a unique OAuth authorization URL. Carefully copy this exact link and paste it into the web browser on your personal laptop. After you verify your credentials, the remote terminal will instantly detect the successful handshake. Your tokens write flawlessly to the persistent host directory, maintaining absolute zero-amnesia status permanently.


Phase 5: Deploying MCP Integration Servers

A terminal agent isolated from current documentation inevitably hallucinates deprecated functions, destroying developer productivity. Elite architectures leverage Model Context Protocol (MCP) servers to grant the agent live operational intelligence. Execute these commands directly inside your running container.

# Integrate Context7 for real-time official documentation retrieval
claude mcp add context7 --scope user -- npx -y @upstash/context7-mcp@latest

# Integrate Serena utilizing the permanently embedded uv package manager
claude mcp add serena -- uvx --from git+[https://github.com/oraios/serena](https://github.com/oraios/serena) \
  serena start-mcp-server --context ide-assistant --project $(pwd)
Enter fullscreen mode Exit fullscreen mode

By connecting Context7, the agent pulls live framework specifications directly into its memory buffer. Integrating Serena elevates the agent from simple text parsing to structural semantic comprehension, allowing it to navigate class hierarchies with absolute precision.

You have eliminated legacy operational flaws completely. By anchoring your deployment on ServerMO Dedicated Servers, combining Rootless Podman isolation with pristine Quadlet systemd architecture, your organization commands an absolute DevSecOps masterpiece ensuring unmatched compilation performance and uncompromising safety.


AI Infrastructure FAQ

Why does systemctl return a "failed to connect to bus" error?
If you switch users using basic commands (su), the Linux environment fails to initialize the DBus session variables required for user-level systemd services. You must establish a fresh SSH connection as the target user to initialize the execution environment flawlessly.

Why does my background container die immediately after starting?
If your container command is set to a standard shell like bash, it will exit instantly because systemd runs it in the background without keyboard input. You must use the sleep infinity command in your Containerfile to keep the process alive perpetually.

Why remove the security flags from the Quadlet configuration?
Many legacy guides hallucinate volume mount flags intended for SELinux environments on Red Hat systems. Ubuntu utilizes AppArmor, making those specific security flags irrelevant. A pristine configuration avoids these unnecessary anomalies.

Will running Claude Code locally eliminate commercial API costs?
No. The agent operates autonomously, reading massive repositories and routing intelligence through the commercial Anthropic API. Unlike fixed-price assistants, this generates dynamic pay-as-you-go costs. You must establish strict billing limits in your developer console to prevent cloud shock invoices.

🔗 Deploy your Enterprise AI Infrastructure today at: ServerMO.com

Top comments (0)