Claude Code on a VPS with tmux and systemd: a dev guide
Run Claude Code on a VPS with tmux and systemd: sessions that outlive SSH, a service that returns after reboot, and credentials in a 0600 file, not .bashrc.
by Ailton Carvalho · AI and automation · November 6, 2026 · 12 min read
In this article
- The short answer
- 1. What "agent on a VPS" really means
- 2. tmux: several windows that don't die with SSH
- 3. systemd: what has to come back after a reboot
- 4. Credential: a 0600 file or EnvironmentFile, never in .bashrc
- 5. Credential precedence and --bare
- 6. Putting the two pieces together: who gets what
- 7. Maintenance and what goes wrong
- A ready-made prompt for your agent
- Frequently asked questions
- Conclusion
The short answer
Running Claude Code on a VPS means keeping a session alive after SSH drops, not leaving an AI to work on its own. It is for people who already have the agent installed and want to organize how they use it: tmux holds the interactive windows, systemd handles what has to come back after a reboot, and the credential lives in a file with restricted permissions. The decision rule is short: work you watch goes in tmux, a routine that has to survive the machine restarting goes in systemd. A secret never goes in .bashrc, because every shell, every child process and every session log inherits it. This guide is the technical version; the non-technical overview, with cost and phone access, is in Claude Code 24/7 on a Hostinger VPS.
1. What "agent on a VPS" really means
Claude Code is a terminal process. If you open it over SSH and the connection drops, the terminal closes and the process dies with it, along with the conversation in progress. Putting the agent on a VPS doesn't change that: it only changes where the process lives. The gain is that the machine stays on, has a stable network and doesn't depend on your laptop.
That leaves two separate problems, and each has its own tool:
- The session has to survive SSH. This is interactive work: you talk to the agent, it edits, you follow along. Tool: tmux.
- The process has to survive a reboot. This is a routine: a job that runs on its own, a service that should be up when the machine boots. Tool: systemd.
Mixing the two is the origin of most hacks (nohup, a forgotten screen, an @reboot cron entry opening tmux without a credential). Solve each one where it belongs.
Prerequisites, according to the documentation read on November 6, 2026: Ubuntu 20.04+ or Debian 10+, 4 GB of RAM or more and an internet connection. The native install and the check look like this:
curl -fsSL https://claude.ai/install.sh | bash
claude --version
claude doctor
According to the same page, claude doctor "prints read-only installation and settings diagnostics without starting a session". Use it after any environment change to see whether the installation is still healthy.
2. tmux: several windows that don't die with SSH
tmux runs programs inside a terminal that you detach and reattach later. The official wiki defines the hierarchy: "Multiple windows are grouped together into sessions" and programs run in panes, each inside a window. In practice, one session per project and one window per function.
Create the named session and detach:
tmux new -s projeto
tmux ls
tmux attach -t projeto
The default prefix is C-b (Ctrl and b). From there: C-b d detaches and leaves everything running, C-b c opens a new window, C-b n and C-b p move forward and back between windows. All of these shortcuts are in the official wiki read today.
A layout that works for anyone who uses Claude Code every day:
| Window | What runs | Why separate |
|---|---|---|
0 agent |
claude in the project folder |
The main conversation, which you follow |
1 tests |
Test suite in watch mode or the development server | Long output that shouldn't clutter the conversation |
2 logs |
tail of the application or service log |
See the effect of what the agent changed |
3 shell |
Free shell for git and inspection | Check the diff without interrupting the agent |
Source of the shortcuts: official tmux wiki, read on November 6, 2026.
A session created by a script
The tmux manual says the new session "is attached to the current terminal unless -d is given". That lets you build the whole environment without attaching: new-session -d -s projeto -n agent -c <FOLDER> creates the session with the first window already named and in the right folder, and new-window -c <FOLDER> adds the others. The has-session command exits with code 1 when the session doesn't exist, which works as a test so the script only creates what is missing. This pattern is useful, but keep the limit in mind: a script that builds tmux after a reboot creates empty windows. It doesn't resume the conversation or load a credential. That is where systemd comes in.
3. systemd: what has to come back after a reboot
tmux does not survive a reboot. The session, the windows and the open claude die with the machine. What has to come back on its own is systemd's job, and an honest caveat belongs here: interactive Claude Code is not a service. A service is a routine without a terminal, and the mode for that is claude -p, the non-interactive mode in the documentation.
User unit and linger
Run the service as your own user, not as root. User units live in $HOME/.config/systemd/user (or $XDG_CONFIG_HOME/systemd/user, if set), according to the systemd.unit manual. There is just one catch: by default the user manager exists only while you are logged in. loginctl enable-linger changes that. In the manual's words: "If enabled for a specific user, a user manager is spawned for the user at boot and kept around after logouts. This allows users who are not logged in to run long-running services."
loginctl enable-linger <USER>
Without linger, the user service disappears when the last SSH session closes. It is the most common mistake for people who test while logged in and find the next day that nothing ran.
The body of the unit
The core is short. Type=exec makes systemd consider the unit started after the binary's exec, and Restart=on-failure restarts only when the process exits with a non-zero code (the manual contrasts it with Restart=always, which restarts "regardless of whether it exited cleanly or not").
[Service]
Type=exec
EnvironmentFile=<USER_HOME>/.config/claude/env
ExecStart=<USER_HOME>/.local/bin/claude -p "<TASK>" --allowedTools "Read"
Restart=on-failure
Add an [Install] section with WantedBy=default.target so it comes up with the user manager. Don't enable the unit yet: it reads a credential file that only exists after the next section, and activation (enable --now) comes at the end of it. The claude path is the one the installation docs give for the native installer: a launcher at ~/.local/bin/claude. systemd does not expand ~, hence the absolute path. Prefer on-failure over always: an authentication error doesn't fix itself, and restarting in a loop a unit that fails because of a credential only repeats the failure.
4. Credential: a 0600 file or EnvironmentFile, never in .bashrc
The thesis of this section fits on one line: the credential lives in a file with restricted permissions and enters the process only when it is born. Putting export in .bashrc makes the secret apply to every shell, every tool the agent launches and every log that captures the environment. The documentation itself treats this as a trap: about CLAUDE_CODE_OAUTH_TOKEN, it tells you to remove the variable "from your shell profile" when you want a /login to hold for later sessions. A forgotten variable in the profile beats the login you just did.
What the documentation guarantees about where the login is stored
On Linux, the login done with /login is stored in ~/.claude/.credentials.json "with file mode 0600". In other words, the interactive path is already a restricted file. For a service without a browser there is the long-token path.
Long token with setup-token
The documentation describes the flow like this: "generate a one-year OAuth token with claude setup-token". The command opens the same authorization flow as /login, prints the token in the terminal and, in the docs' words, "does not save the token anywhere". Keeping it is up to you:
claude setup-token
mkdir -p ~/.config/claude
install -m 600 /dev/null ~/.config/claude/env
Open the file in your editor and write a single line, CLAUDE_CODE_OAUTH_TOKEN=<TOKEN>, without quotes and without export. Because the token appears in the terminal, close that tmux window after copying it. EnvironmentFile= reads "newline-separated variable assignments", ignores empty lines and lines starting with # and, if the path starts with -, treats the file as optional. For a credential service, leave out the -: a missing file has to fail loudly, not run without authentication.
Two limits the documentation places on this token, and they change the design:
- It requires a Pro, Max, Ultra, Team or Enterprise plan.
- It "can only make model requests": it doesn't open a Remote Control session or fetch claude.ai connectors. Locally configured MCP keeps working (see MCP in Claude Code and Cursor).
The honest limit of EnvironmentFile
The systemd.exec manual is direct: environment variables "are not suitable for passing secrets" and those set for a unit are exposed to unprivileged clients over D-Bus. For a real secret, the docs point to LoadCredential=, LoadCredentialEncrypted= and SetCredentialEncrypted=. On a single-user VPS, an EnvironmentFile with mode 0600 is a reasonable middle ground, but it is a middle ground: if the machine has more people on it, study systemd credentials before using a long token.
With the file created and the token written, enable the unit:
systemctl --user daemon-reload
systemctl --user enable --now claude-rotina.service
5. Credential precedence and --bare
When more than one credential is present, Claude Code picks only one, in this order (documentation read on November 6, 2026):
| Order | Credential | Note from the docs |
|---|---|---|
| 1 | Cloud provider (CLAUDE_CODE_USE_BEDROCK, CLAUDE_CODE_USE_VERTEX or CLAUDE_CODE_USE_FOUNDRY) |
When the variable is set |
| 2 | ANTHROPIC_AUTH_TOKEN |
Sent as Authorization: Bearer, for gateways |
| 3 | ANTHROPIC_API_KEY |
In -p, "the key is always used when present" |
| 4 | apiKeyHelper output |
Dynamic or rotating credentials |
| 5 | CLAUDE_CODE_OAUTH_TOKEN |
Long token from claude setup-token |
| 6 | Anthropic profile and federation credentials | Their own ranking rules against /login |
| 7 | Subscription login from /login |
Default for Pro, Max, Ultra, Team and Enterprise |
Source: Authentication, Claude Code Docs.
The practical reading comes from the text itself: with an active subscription and ANTHROPIC_API_KEY in the environment, "Claude Code uses the API key once you approve it". The docs warn that this "can cause authentication failures if the key belongs to a disabled or expired organization". The diagnosis is the one the docs give: unset ANTHROPIC_API_KEY and check the active method with /status. On a VPS, where you have .bashrc, a unit and the tmux shell, it is easy to end up with two credentials coming from different places.
What --bare changes
--bare cuts the automatic loading of "hooks, skills, custom commands, subagents, installed plugins, MCP servers, auto memory, and CLAUDE.md". The docs call it recommended for scripts and the SDK and warn that it "will become the default for -p in a future release". But it has a direct consequence for credentials: "In bare mode, Claude Code never reads OAuth credentials or the system keychain." And on the authentication page: "Bare mode does not read CLAUDE_CODE_OAUTH_TOKEN. If your script passes --bare, authenticate with ANTHROPIC_API_KEY or an apiKeyHelper instead."
Translated to the unit: the setup-token token and --bare don't go together. Whoever picks --bare uses ANTHROPIC_API_KEY with a key created in the Claude Console (the docs say the mode "doesn't use your subscription login"); whoever wants the subscription uses the long token without --bare. Without --bare, -p runs the hooks from .claude/settings.json and connects the servers from the project's .mcp.json, "even in a folder you've never trusted", according to the programmatic-usage docs. In a service, that matters: whatever is versioned in the folder starts running with nobody watching.
6. Putting the two pieces together: who gets what
With both tools understood, the split becomes mechanical. The interactive tmux window uses the normal subscription login (/login), which is the path the docs describe for daily use and the only one that keeps features such as Remote Control and claude.ai connectors. The systemd unit uses the long token, because there is no browser for a login. That is two credentials for two uses, and the precedence from the previous section decides which one applies in each process.
| Need | Where it runs | Credential |
|---|---|---|
| Chat, review a diff, work while watching | agent window in tmux |
/login login |
| Scheduled routine or task without a terminal | User unit in systemd | CLAUDE_CODE_OAUTH_TOKEN in the EnvironmentFile |
| Reproducible script, identical on any machine | Unit or shell with --bare |
ANTHROPIC_API_KEY or apiKeyHelper |
Source: Authentication and programmatic usage, Claude Code Docs, read on November 6, 2026.
Two environment traps show up here. The first: the tmux shell inherits the environment from when it was created. If you exported a credential variable afterwards, the old windows don't see it, and the new ones may see it without you noticing. That is why the file rule applies to tmux too: no export of a secret in the shell where the agent runs. The second: a routine task that systemd fires on each run is a new conversation. To continue the previous one, the docs offer --continue and --resume with the session ID, but deciding whether a routine needs memory between runs is a project decision, not a configuration one.
To schedule the routine by time, the same logic applies (scheduling itself is another subject, covered in a separate article on the site once it is published). What matters here is that the service has a credential, minimal permission and a way to fail visibly.
Minimal permission in the unit
In the section 3 example, --allowedTools "Read" grants read-only access. The docs explain that --allowedTools lets Claude use certain tools "without prompting", and that in a manual-mode claude -p a call that needs approval "is denied unless something approves it". For a service with nobody watching, that is the desired behavior: whatever wasn't explicitly allowed is denied. Allow by prefix, such as Bash(git diff *), instead of a bare Bash. The docs also include --permission-prompts none (from v2.1.259) for runs where nobody answers prompts.
7. Maintenance and what goes wrong
Four points that tend to bite after the first week, all based on the documentation read today:
- An expiring login. When the
/loginlogin is less than three days from expiring, Claude Code showsYour login expires in 3 days · run /login to renew. The docs warn that a background or Remote Control session "that outlives the login stops making progress" until you sign in again. Note the date of thesetup-tokentoo: the token lasts one year. - Automatic updates. The native install updates in the background and the new version applies the next time
claudestarts. If you need to pin the version in a service,DISABLE_AUTOUPDATERwith the value"1"in theenvofsettings.jsonturns off only the background check;claude updatekeeps working. - A clean stop. Stopping a
claude -pthrough a process supervisor (SIGTERM) ends it with code 143 and the turn in progress is left without a result. To finish the turn first, the docs say to send SIGINT. - Two credentials competing. If the service fails with an authentication error right after you set up an API key somewhere else, check the order in section 5 before generating a new token.
Three checks are enough to prove the setup is up:
tmux ls
systemctl --user status claude-rotina.service
claude doctor
The first shows the live session. The second has to be read with the unit type in mind: it runs claude -p once and exits, so after a successful task the normal state is inactive (dead) with status=0/SUCCESS on the last cycle, and Restart=on-failure does not restart it. To see the task output, use journalctl --user -u claude-rotina.service -n 20. The third (together with /status inside Claude Code, which shows the authentication method in use) confirms the installation and the credential. The test that really matters is the reboot: restart the VPS, log in again and check in status and journalctl whether the unit ran on its own at boot and finished with status=0/SUCCESS. If it did, linger and the EnvironmentFile are right; if the state is failed, the journal shows the credential or path error.
If what you need goes beyond this (an agent reading an ERP, a store or a database, with a queue and webhooks), the design changes from "a session that survives" to a custom integration. If you are starting from the cost and phone-access side, you will find the path in the article Claude Code 24/7 on a Hostinger VPS.
A ready-made prompt for your agent
Paste the text below into an AI agent session already open on the VPS (such as Claude Code itself). It checks the prerequisites, builds the tmux session, configures linger and the systemd unit, and prepares the credential file without reading its contents. The steps that depend on you (authorizing in the browser and pasting the token) it hands back to you.
Always reply in English.
Reader data:
- Linux user on the VPS: <USER>
- Project folder: <PROJECT_FOLDER>
- tmux session name: <TMUX_SESSION>
- Routine task (the claude -p text): <TASK>
Rules:
1. Never print, paste into the chat or write to a versioned file any password, token, API key or login code.
2. Show each command before running it and stop at the exact error, without trying to work around it.
3. Do not invent commands; use only those on this list.
Steps, in this order:
1. Prerequisites: Ubuntu 20.04+ or Debian 10+ and 4 GB of RAM or more. If they are not met, stop and tell me.
2. Installation: curl -fsSL https://claude.ai/install.sh | bash, then claude --version and claude doctor.
3. tmux: tmux new -s <TMUX_SESSION>; create the windows agent, tests, logs and shell in the project folder with C-b c. Detach with C-b d and check with tmux ls.
4. Linger: loginctl enable-linger <USER>.
5. Unit at ~/.config/systemd/user/claude-rotina.service with Type=exec, EnvironmentFile=<absolute path of the env file>, ExecStart=<absolute path of claude> -p "<TASK>" --allowedTools "Read", Restart=on-failure and [Install] WantedBy=default.target. Do not enable it yet.
6. Token: ask ME to run claude setup-token, authorize in the browser and copy the token. You do not read or repeat the token.
7. Credential file: mkdir -p ~/.config/claude and install -m 600 /dev/null ~/.config/claude/env. Ask ME to write the line CLAUDE_CODE_OAUTH_TOKEN=<TOKEN> into it, without quotes and without export. No credential in .bashrc.
8. Activation, only after the file exists with the token: systemctl --user daemon-reload and systemctl --user enable --now claude-rotina.service.
9. If I use --bare in any script, warn me that --bare does not read CLAUDE_CODE_OAUTH_TOKEN and requires ANTHROPIC_API_KEY or apiKeyHelper.
Final validation:
- tmux ls shows the session <TMUX_SESSION>.
- systemctl --user status claude-rotina.service shows status=0/SUCCESS on the last cycle (the unit runs once and stays inactive (dead), which is expected) and journalctl --user -u claude-rotina.service -n 20 shows the task output.
- claude doctor reports no error.
- Ask ME to reboot the VPS and confirm, through status and journalctl, that the unit ran on its own at boot and finished with status=0/SUCCESS.
If any check fails, stop and show the exact error; do not claim it is finished.
Frequently asked questions
Do I need tmux if I already use systemd?
Yes, for different uses. systemd keeps a process running without a terminal and restarts it according to the unit's policy. tmux keeps an interactive session that you open and close at will, with claude talking to you. If you only have systemd, you can't watch the agent live; if you only have tmux, you lose everything on reboot.
Can I put the token in .bashrc just to test?
Avoid it, even for a test. .bashrc applies to every shell you open, and the documentation also warns that a forgotten CLAUDE_CODE_OAUTH_TOKEN in the profile makes Claude Code switch credentials without you noticing. A file with mode 0600 read by EnvironmentFile gives the same result without spreading the secret.
Does --bare work with the claude setup-token token?
No. The documentation says: "Bare mode does not read CLAUDE_CODE_OAUTH_TOKEN. If your script passes --bare, authenticate with ANTHROPIC_API_KEY or an apiKeyHelper instead." If the script uses --bare, the credential is a Console API key or an apiKeyHelper.
Why does my service disappear when I close SSH?
Linger is probably missing. Without loginctl enable-linger, the user manager only exists while there is an open session and takes the services down with it. Enable it for your user, reload the units and test by closing SSH and logging back in.
Does the setup-token token work for Remote Control?
No. The docs are explicit: the token "can only make model requests", so it doesn't establish Remote Control sessions or fetch claude.ai connectors. For those features, use the /login login in the interactive window.
Conclusion
An agent on a VPS is a session that survives your connection, and the right design separates what is interactive (several windows in tmux) from what has to come back on its own (a user unit, with linger). The credential stays in a restricted file, never in .bashrc, and --bare comes in only when you accept trading the token for an API key. Every credential fact here comes from the Claude Code documentation read on November 6, 2026; check the version you have before copying. If what you need is the agent reading your ERP, your store or your database, that is a custom integration (MCP, webhook, queue). Describe the system and what you want to automate at