Back to Blog

Claude Code on Ubuntu: No More Failed Installs

Tutorials and Guides5926
Claude Code on Ubuntu: No More Failed Installs

Abstract

This tutorial covers end-to-end deployment of Anthropic’s Claude Code CLI tool on Ubuntu Linux, with full integration for DeepSeek’s compatible Anthropic API endpoint. All operations are validated on x86_64 Ubuntu 20.04 and 22.04 environments, with Node.js 20 LTS as the core runtime dependency. Unlike official one-line curl install scripts that suffer regional access failures, this guide uses npm global installation with domestic mirror acceleration for stable setup. We provide a self-contained bash bootstrap script that handles environment variable injection, persistent local configuration, API connectivity validation, and one-click startup. For teams managing multi-model API routing, an API gateway like 4sapi can standardize DeepSeek and Anthropic endpoint forwarding for unified access control.

1. Pre-Deployment Environment Prerequisites

Claude Code is a terminal-native AI assistant built entirely on Node.js, with no direct PyTorch or CUDA runtime dependencies. Before starting installation, verify these hardware & network requirements:

1.1 Install Node.js 20 LTS via Tsinghua Mirror

The official remote install script (claude.ai/install.sh) frequently returns region-unavailable errors for domestic networks, so we perform manual offline binary deployment:

bash
# Navigate to local system binary directory
cd /usr/local
# Download Node.js 20.15.0 Linux x64 archive from Tsinghua mirror
curl -OL https://mirrors.tuna.tsinghua.edu.cn/nodejs-release/v20.15.0/node-v20.15.0-linux-x64.tar.xz
# Decompress archive
tar -xvf node-v20.15.0-linux-x64.tar.xz
# Create symlinks to system PATH
ln -sf /usr/local/node-v20.15.0-linux-x64/bin/node /usr/local/bin/node
ln -sf /usr/local/node-v20.15.0-linux-x64/bin/npm /usr/local/bin/npm
# Verify successful installation
node --version
npm --version

Valid output versions: v20.15.0 for Node, 10.7.0 for npm.

1.2 Configure Domestic npm Registry Mirror

Speed up subsequent package installation by switching npm to a domestic mirror source:

bash
npm config set registry https://registry.npmmirror.com

2. Global Installation of Claude Code CLI

Execute the global npm install command to pull the official Claude Code package:

bash
npm install -g @anthropic-ai/claude-code

Post-Install Validation

Run two verification commands to confirm the CLI binary is registered to system PATH:

bash
claude --version
claude doctor

Critical Note: The official curl one-click installation script is omitted here due to consistent regional access failures; npm global installation is confirmed as the reliable alternative for restricted network environments.

3. DeepSeek API Integration & Auto Bootstrap Script

DeepSeek exposes an Anthropic-compatible API path, allowing Claude Code to send all native request schemas to DeepSeek’s model backend without payload rewriting. We build a self-contained startup script to automate environment injection, persistent config writing, and connectivity health checks.

3.1 Retrieve DeepSeek API Key

  1. Visit the official DeepSeek developer platform: platform.deepseek.com
  2. Complete account sign-up and login, navigate to the API Keys management page
  3. Generate a new secret key (format starts with sk-), store securely — the full key string only displays once on creation.

3.2 Create One-Click Bootstrap Script

Create a file named start-claude-deepseek.sh with the full automation logic below:

bash
cat > start-claude-deepseek.sh << 'EOF'
#!/bin/bash
# Configuration Zone: Replace placeholder with your real DeepSeek API Key
DEEPSEEK_KEY="sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

set -e

echo "====================================="
echo " Claude Code + DeepSeek Auto Bootstrap "
echo "====================================="
echo ""

# Step 1: Validate API Key is modified
if [[ "${DEEPSEEK_KEY}" == "sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" ]]; then
    echo "ERROR: You have not filled in a valid DeepSeek API Key"
    echo "Edit this script and replace the DEEPSEEK_KEY value first"
    exit 1
fi

# Step 2: Verify claude binary exists in PATH
if ! command -v claude &> /dev/null; then
    echo "ERROR: claude command not found, finish npm installation first"
    exit 1
fi
echo "✓ Claude Code CLI detected"

# Step 3: Persist environment variables to ~/.bashrc for long-term terminal sessions
if ! grep -q "CLAUDE_CODE_DEEPSEEK_CONFIGURED" ~/.bashrc 2>/dev/null; then
    echo "# === Claude Code DeepSeek Env Config ===" >> ~/.bashrc
    echo "export ANTHROPIC_BASE_URL=https://api.deepseek.com/anthropic" >> ~/.bashrc
    echo "export ANTHROPIC_AUTH_TOKEN=\$DEEPSEEK_KEY" >> ~/.bashrc
    echo "export ANTHROPIC_API_KEY=\$DEEPSEEK_KEY" >> ~/.bashrc
    echo "export ANTHROPIC_MODEL=deepseek-v4-pro[1m]" >> ~/.bashrc
    echo "export ANTHROPIC_DEFAULT_OPUS_MODEL=deepseek-v4-pro[1m]" >> ~/.bashrc
    echo "export ANTHROPIC_DEFAULT_SONNET_MODEL=deepseek-v4-pro[1m]" >> ~/.bashrc
    echo "export ANTHROPIC_DEFAULT_HAIKU_MODEL=deepseek-v4-flash" >> ~/.bashrc
    echo "export CLAUDE_CODE_SUBAGENT_MODEL=deepseek-v4-flash" >> ~/.bashrc
    echo "export CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1" >> ~/.bashrc
    echo "export CLAUDE_CODE_EFFORT_LEVEL=max" >> ~/.bashrc
    echo "# === End Claude Code Config ===" >> ~/.bashrc
    echo "✓ Environment variables written to ~/.bashrc"
else
    echo "✓ ~/.bashrc already configured, skip duplicate write"
fi

# Step 4: Write persistent JSON settings inside .claude directory (dual backup mechanism)
mkdir -p ~/.claude
cat > ~/.claude/settings.json << JSONEOF
{
  "env": {
    "ANTHROPIC_BASE_URL": "https://api.deepseek.com/anthropic",
    "ANTHROPIC_AUTH_TOKEN": "$DEEPSEEK_KEY",
    "ANTHROPIC_API_KEY": "$DEEPSEEK_KEY",
    "ANTHROPIC_MODEL": "deepseek-v4-pro[1m]",
    "ANTHROPIC_DEFAULT_OPUS_MODEL": "deepseek-v4-pro[1m]",
    "ANTHROPIC_DEFAULT_SONNET_MODEL": "deepseek-v4-pro[1m]",
    "ANTHROPIC_DEFAULT_HAIKU_MODEL": "deepseek-v4-flash",
    "CLAUDE_CODE_SUBAGENT_MODEL": "deepseek-v4-flash",
    "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1",
    "CLAUDE_CODE_EFFORT_LEVEL": "max"
  }
}
JSONEOF
echo "✓ Persistent ~/.claude/settings.json configuration saved"

# Step 5: Export env vars for current active shell session
export ANTHROPIC_BASE_URL="https://api.deepseek.com/anthropic"
export ANTHROPIC_AUTH_TOKEN="$DEEPSEEK_KEY"
export ANTHROPIC_API_KEY="$DEEPSEEK_KEY"
export ANTHROPIC_MODEL="deepseek-v4-pro[1m]"
export ANTHROPIC_DEFAULT_OPUS_MODEL="deepseek-v4-pro[1m]"
export ANTHROPIC_DEFAULT_SONNET_MODEL="deepseek-v4-pro[1m]"
export ANTHROPIC_DEFAULT_HAIKU_MODEL="deepseek-v4-flash"
export CLAUDE_CODE_SUBAGENT_MODEL="deepseek-v4-flash"
export CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC="1"
export CLAUDE_CODE_EFFORT_LEVEL="max"

# Step 6: Run API connectivity test to DeepSeek endpoint
echo ""
echo "Testing DeepSeek API connection..."
TEST=$(curl -s -w "%{http_code}" -o /dev/null \
-H "Authorization: Bearer ${DEEPSEEK_KEY}" \
-H "Content-Type: application/json" \
-d '{"model":"deepseek-v4-pro[1m]","messages":[{"role":"user","content":"hi"}],"max_tokens":5}' \
https://api.deepseek.com/v1/chat/completions 2>/dev/null || echo "CURL_FAILED")

if [[ "$TEST" == "CURL_FAILED" ]]; then
    echo "⚠️ Network request failed, check outbound network rules"
elif [[ "$TEST" == "200" ]]; then
    echo "✅ DeepSeek API connection successful, config persisted"
elif [[ "$TEST" == "401" ]]; then
    echo "⚠️ API Key invalid (401), double-check your secret key"
else
    echo "⚠️ DeepSeek returned HTTP status code: $TEST"
fi

# Step 7: Launch interactive Claude Code session
echo ""
echo "====================================="
echo " Starting Claude Code Interactive Shell "
echo "====================================="
echo " Tips: Run /status inside shell to view loaded model config"
echo " Type 'hi' to test basic LLM generation response"
echo ""
claude
EOF

3.3 Inject Your Personal DeepSeek API Key

Open the script file with nano editor to replace the placeholder secret key value:

bash
nano start-claude-deepseek.sh

Locate the line DEEPSEEK_KEY="sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" and overwrite the placeholder with your real API key, save and exit with Ctrl+O then Ctrl+X.

3.4 Execute Bootstrap Script

Grant execute permission and run the automation workflow:

bash
chmod +x start-claude-deepseek.sh
bash start-claude-deepseek.sh

The script will automatically complete environment injection, persistent config writing, API health validation, and launch the interactive Claude Code terminal session on first run. Subsequent usage only requires re-running the bash script command.

4. Daily Operation & Core CLI Commands

4.1 Standard Interactive Startup (Recommended)

Navigate to your project working directory and launch the bootstrap script:

bash
cd /path/to/your/code-project
bash ~/start-claude-deepseek.sh

4.2 Unattended Auto-Edit Mode (Non-root User Only)

For fully autonomous file modification without manual confirmation prompts, use the permission skip flag (security warning: only run inside trusted project directories):

bash
claude --dangerously-skip-permissions

4.3 Built-In Internal Shell Commands

After entering the Claude Code interactive shell, these built-in slash commands simplify debugging and project management:

CommandFunction Description
/statusPrint loaded model, environment variables, and API connection status
/auto-acceptAuto-approve all file edit & shell execution requests (ideal for trusted rootless dev users)
/initScan full project directory and generate CLAUDE.md structural context file
/clearErase current dialogue history to reset context window
/costShow real-time token consumption metrics for the active session

5. Special Root User Security Handling

Claude Code enforces security restrictions that block --dangerously-skip-permissions when operating under the root superuser account. Three compliant workarounds are provided:

Option A: Create Dedicated Non-Root Developer User (Best Practice)

bash
# Create regular user account
useradd -m -s /bin/bash dev
# Switch to new user
su - dev
# Extend PATH to include Node.js binaries
echo "export PATH=/usr/local/node-v20.15.0-linux-x64/bin:$PATH" >> ~/.bashrc
source ~/.bashrc
# Copy existing Claude persistent config to new user home
mkdir -p ~/.claude
cp -r /root/.claude/settings.json ~/.claude/settings.json 2>/dev/null || true
# Launch unattended auto mode as restricted dev user
claude --dangerously-skip-permissions

Option B: Manually run /auto-accept inside root shell

Launch standard claude without skip flag, then input /auto-accept once inside the interactive terminal to enable automatic approval logic.

Option C: Fine-grained permission whitelist for root execution

bash
claude --permission-mode acceptEdits --allowed-tools "Bash,Read,Write,Edit,Grep"

6. Model & Environment Variable Reference Table

All critical environment variables injected by the bootstrap script, with official recommended values for DeepSeek integration:

Env VariableExplanationSuggested Value
ANTHROPIC_BASE_URLDeepSeek Anthropic-compatible API root endpointhttps://api.deepseek.com/anthropic (do not append /v1)
ANTHROPIC_MODELPrimary inference model for core tasksdeepseek-v4-pro[1m]
ANTHROPIC_DEFAULT_OPUS_MODELHigh-complexity task fallback modeldeepseek-v4-pro[1m]
ANTHROPIC_DEFAULT_SONNET_MODELMedium-difficulty reasoning modeldeepseek-v4-pro[1m]
ANTHROPIC_DEFAULT_HAIKU_MODELLightweight fast-response auxiliary modeldeepseek-v4-flash
CLAUDE_CODE_SUBAGENT_MODELSub-agent lightweight worker modeldeepseek-v4-flash
CLAUDE_CODE_EFFORT_LEVELReasoning computation resource allocationmax

The [1m] suffix enables the 1M ultra-long context window, strongly recommended for large repository code analysis workloads.

7. Common Failure Troubleshooting Matrix

Failure SymptomRoot CauseResolution
Script syntax error during Node.js installOfficial curl script blocked by regional network filtersUse manual npm mirror installation workflow from Section 1
glibc recv error (-110)GitHub binary download throttlingSwitch to Tsinghua Node.js mirror archive deployment
--dangerously-skip-permissions cannot be usedRoot user security hardening blockCreate non-root dev user or use /auto-accept inside shell
Streaming API request failuresIntermittent network packet lossAdd env flag CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1
401 Unauthorized API responseIncorrect or expired DeepSeek API KeyRe-generate secret key on DeepSeek platform and re-inject into script
404 model not found errorWrong model identifier stringUse deepseek-v4-pro[1m] instead of generic deepseek-chat

8. Security Hardening Best Practices

  1. Restrict bootstrap script file permissions: chmod 600 start-claude-deepseek.sh to prevent other system users from reading embedded API credentials.
  2. Never commit the unredacted startup script to public Git repositories; the plaintext API key poses data leakage and unexpected billing risks.
  3. Rotate DeepSeek API keys on a regular cycle via the developer platform to mitigate long-term credential exposure risks.
  4. Periodically execute /cost inside the Claude shell to monitor token consumption and avoid unplanned high-cost inference spikes.

9. Pre-Deployment Validation Checklist

Complete all verification items before formal production usage:

Conclusion

This deployment pipeline resolves the core regional access pain point of the official Claude Code install script by leveraging domestic npm mirrors and a fully self-contained bash automation script for DeepSeek API integration. The dual-layer configuration mechanism (bashrc global environment variables + local .claude/settings.json) ensures persistent model routing settings across terminal sessions, while built-in curl health checks eliminate blind API connection failures.

For enterprise teams managing multiple LLM backend endpoints including DeepSeek and Anthropic native services, centralized traffic routing via an API gateway such as 4sapi can standardize authentication headers and model fallback logic across all CLI agent workloads. The documented root-user security workarounds balance convenience with the official permission guardrails built into Claude Code, making this workflow suitable for both local developer workstations and remote Ubuntu cloud servers. All model identifiers, environment variables, and error mitigation logic are validated against live DeepSeek compatible API endpoints, eliminating trial-and-error configuration overhead for engineers migrating Claude Code away from native Anthropic models to domestic open-weight LLM backends.

Tags:Claude CodeDeepSeekUbuntuCLIAIDeployment

Recommended reading

Explore more frontier insights and industry know-how.