---
title: "Deploy Claude Code Headless"
description: "Run Claude Code non-interactively with claude -p on a server"
category: "AI/ML"
url: https://railway.com/deploy/deploy-claude-code-headless-mode
---

# Deploy Claude Code Headless

Run Claude Code non-interactively with claude -p on a server

**[Deploy Claude Code Headless on Railway](https://railway.com/template/deploy-claude-code-headless-mode)**

Machine-readable deploy manifest (JSON, validated by TemplateCI): https://railway.com/deploy/deploy-claude-code-headless-mode/manifest.json

- **Creator:** onepush
- **Category:** AI/ML

## Template content

### Ubuntu https://github.com/anthropics.png

- **Image:** ghcr.io/onepush-dev/ubuntu-claude-code:26.04-claude2.1.314
- **Public domain:** Yes

## Documentation

# Deploy and Host self hosted Claude Code Headless (Headless Claude Code on a Self-Hosted Box) on Railway

This template runs Claude Code non-interactively with `claude -p` on an always-on Railway box.

## About Hosting Claude Code Headless open-source software on Railway (self hosted Running Claude Code non-interactively via claude -p on an always-on Railway server template)

This template gives you an Ubuntu 26.04 box with Claude Code 2.1.314 installed globally, so you can run `claude -p "your prompt"` from cron or SSH and keep the output.

## Why Deploy Claude Code Headless, the GitHub Actions alternative on Railway (Railway Free Trial)

GitHub Actions is the usual home for Claude Code jobs, but each run starts on a cold runner and bills by the minute.

Railway is a singular platform to deploy your infrastructure stack. Railway will host your infrastructure so you don't have to deal with configuration, while allowing you to vertically and horizontally scale it.

By deploying Claude Code Headless on Railway, you are one step closer to supporting a complete full-stack application with minimal burden. Host your servers, databases, AI agents, and more on Railway.

### Railway vs Other Hosting Providers and VPS for Claude Code Headless self hosting

Picking where a headless Claude Code box lives comes down to how much server work you want to own.

| Provider | What You Get with Railway | What You Get with the Other Provider |
|---|---|---|
| DigitalOcean | Ubuntu 26.04, Claude Code 2.1.314, tmux and a persistent /home volume ready to go. | A bare Droplet where you install Claude Code, configure sshd and tmux, and set up the firewall. |
| AWS | One service with a generated TERMINAL_PASSWORD and a TCP proxy for SSH. | Full EC2 and EBS control, with more setup before your first claude -p run. |
| Hetzner | Managed networking and restarts, with no OS upkeep. | Low-cost servers where you own patching, cron or systemd jobs, and backups. |

## Common Use Cases for hosted Claude Code Headless

- **Nightly repo review:** Schedule `claude -p "Review yesterday's commits for security issues" --output-format json` in cron, then pipe `jq -r '.result'` into a dated report file on `/home`.
- **Resumable refactor:** Capture the `session_id` from one run and pass it to `--resume` on later runs, so a large refactor spans several invocations without losing context.
- **Capped batch jobs:** Combine `--max-turns` with `--max-budget-usd` to bound an unattended run, leaving headroom since the budget cap is a client-side estimate.
- **Live stream-json watching:** Run `--output-format stream-json --verbose` inside tmux, then reattach over SSH from another device to follow the events as they arrive.
- **CI-style gates:** Branch on the non-zero exit code, and fail the check when `mcp_server_errors` is non-empty in the `system/init` event.

## Dependencies for Claude Code Headless Docker hosted on Railway

This template is one Ubuntu 26.04 LTS service with Claude Code 2.1.314 installed globally as `claude`, plus Node.js 22, npm, Python 3, git, and ripgrep.

### Deployment Dependencies for Managed Claude Code Headless Service (Claude Code + ttyd + OpenSSH + tmux)

- **Image:** `ghcr.io/onepush-dev/ubuntu-claude-code:26.04-claude2.1.314`, built on ttyd 1.7.7, OpenSSH, and tmux 3.6.
- **Ports:** 7681 for the browser terminal (HTTP basic auth) and 2222 for SSH through the Railway TCP proxy.
- **Volume:** mount at `/home` for `~/.claude` login state, repos, and SSH host keys.
- **Variables:** `TERMINAL_USER=ubuntu`, `TERMINAL_PASSWORD` (generated per deploy), `TMUX_SESSION=main`, and optionally `ANTHROPIC_API_KEY`.

### Implementation Details for Claude Code Headless (Using Ubuntu + Claude Code official docker image)

Set `ANTHROPIC_API_KEY` as a service variable and redeploy, because the entrypoint writes it to `/etc/railway-claude.env`.

## How does Claude Code Headless compare against other ways to run Claude Code headless and automate agent jobs

### Claude Code Headless vs Claude Agent SDK (Programmatic Agent Control)

- **Where Headless wins:** You get a finished CLI you can call from cron with `claude -p`, and the box keeps your login between runs.
- **Where the SDK wins:** For custom tools or streaming events inside your own application, the Python and TypeScript packages give you direct control.
- **Practical note:** Headless jobs are shell pipelines, so you branch on exit codes and parse `--output-format json` with `jq`.

### Claude Code Headless vs GitHub Actions with Claude Code (CI/CD Automation)

- **Where Headless wins:** Long runs stay alive in tmux on an always-on server, so you can reattach over SSH instead of reading a workflow log.
- **Where Actions wins:** Jobs trigger on repository events like pull requests with no server to maintain.
- **Practical note:** You can gate a check on `mcp_server_errors` or a non-zero exit from either setup.

### Claude Code Headless vs Codex CLI exec (Non-Interactive OpenAI Agent)

- **Where Headless wins:** It runs Claude Code, so your `ANTHROPIC_API_KEY` or login persists on `/home` and is reused by every job.
- **Where Codex wins:** If your team standardizes on OpenAI models, the `exec` subcommand fits that stack with no extra setup.
- **Practical note:** Both are non-interactive command-line agents, so the scripting patterns look broadly similar.

### Claude Code Headless vs Cursor background agents (Cloud-Hosted Agents)

- **Where Headless wins:** The job runs on a machine you control, with repos and MCP config kept on the volume between redeploys.
- **Where Cursor wins:** Background agents need no server and are managed for you, which suits teams that do not want to run infrastructure.
- **Practical note:** Any tool you install under `/home` is available to every headless run here.

## How to use Claude Code Headless (the OSS Headless Claude Code on a Self-Hosted Box)?

Run these steps on day one. Sign in first, since headless jobs cannot authenticate otherwise.

1. Sign in once by running `claude` in the browser terminal or over SSH, or set `ANTHROPIC_API_KEY` as a service variable and redeploy so `/etc/railway-claude.env` is written.
2. Attach to the shared session with `tmux attach -t main`, or start a dedicated one with `tmux new-session -d -s jobs`.
3. Run a headless job with a tool allowlist and a turn cap.
4. Get structured output by piping the JSON response through `jq`.
5. Capture a session ID and resume that conversation in the next run.
6. Detach with Ctrl-b then d so the job keeps running after you disconnect.

```bash
claude
tmux attach -t main
tmux new-session -d -s jobs
claude -p "Find and fix the bug in auth.py" --allowedTools "Read,Edit,Bash" --max-turns 3
claude -p "Summarize this project" --output-format json | jq -r '.result'
session_id=$(claude -p "Start a review" --output-format json | jq -r '.session_id')
claude -p "Continue that review" --resume "$session_id"
```

## How to self host Claude Code Headless on other VPS Services (Ubuntu + Claude Code self hosting guide)

Run the same image on a plain Ubuntu VPS if you want full control of the host. Headless `claude -p` jobs work the same way as on Railway.

### Clone the Repository

```bash
git clone https://github.com/onepush-dev/ubuntu-claude-code.git
cd ubuntu-claude-code && git checkout 658fc7d
```

### Install Dependencies

```bash
sudo apt-get update && sudo apt-get install -y docker.io
sudo docker build -t ubuntu-claude-code:local .
```

### Configure Environment Variables

Keep the file readable only by root, since it holds your key and terminal password.

```bash
printf 'ANTHROPIC_API_KEY=your-api-key\nTERMINAL_PASSWORD=your-generated-password\n' > claude.env
chmod 600 claude.env
```

### Start the Claude Code Headless Application

Mount a volume at `/home` so repos, the `~/.claude` login and SSH host keys persist.

```bash
sudo docker run -d --name claude-headless --restart always \
  --env-file claude.env -p 7681:7681 -p 2222:2222 \
  -v claude-home:/home ubuntu-claude-code:local
```

Put TLS in front of port 7681 at your-domain, then connect with `ssh -p 2222 ubuntu@your-domain`.

## Official Pricing of Claude Code Headless (Ubuntu + Claude Code pricing)

Claude Code Headless is free and open source, so this project charges no license fee.

## Claude Code Headless cloud vs self hosted comparison (Pricing, features, costs, and more)

Self-hosting Claude Code headless on this always-on box keeps your claude -p jobs running after you close the laptop, and you can reattach to tmux from another device.

### Monthly cost of self hosting Claude Code Headless on Railway

Railway bills by resource usage, so the box costs what it consumes while running, plus the volume holding /home.

### System Requirements for Hosting Claude Code Headless on a VPS

On a VPS you need Ubuntu 26.04 LTS or a similar release, Node.js 22 with npm for the claude CLI, and enough memory and disk for your repos and job output.

## Frequently Asked Questions (FAQs)

### Does my API key survive a redeploy?

Yes, if you set it as a service variable. Your `~/.claude` login persists on `/home` either way.

### Why does my claude -p run stop after 10 minutes?

By default Claude Code stops remaining background work, such as background commands or subagents, after 10 minutes of idle waiting.

### How do I resume a session from a new SSH login?

Find the session ID from your earlier JSON output, then run `claude -p "Continue that review" --resume "SESSION_ID"` from the same working directory.

### Does --max-budget-usd guarantee a hard spend cap?

No, it checks a client-side cost estimate that can differ from your bill.

### How do I stop a run cleanly without losing the turn?

Send SIGINT (Ctrl-C) first so the current turn ends cleanly. A SIGTERM exits with code 143 and records no result for the in-progress turn.

### Is there a built-in scheduler for recurring jobs?

No, use cron or a loop in tmux.


## Similar templates

- [Chat Chat](https://railway.com/deploy/-WWW5r) — Chat Chat, your own unified chat and search to AI platform.
- [Weaviate](https://railway.com/deploy/weaviate-1) — Vector database with hybrid search and an API key-protected API
- [Möbius v0.1 Personal AI OS](https://railway.com/deploy/mobius-v01-personal-ai-os) — Self-hosted AI agent that builds and runs apps for you, with memory.

Open this page in a browser: https://railway.com/deploy/deploy-claude-code-headless-mode
