Installing Automatic1111 Stable Diffusion WebUI on Ubuntu with Docker: A Comprehensive Guide

Written by:

This guide provides a step-by-step process for setting up Automatic1111 Stable Diffusion WebUI on Ubuntu 20.04 and newer using Docker. You’ll learn how to properly configure, secure, and access your installation from multiple devices, including through WSL and custom domain names with Pi-hole.

Introduction: Understanding Automatic1111 and Docker Deployment

Automatic1111’s Stable Diffusion Web UI is a popular interface for generating AI images. Deploying it with Docker provides several advantages:

  • Consistent environment across different systems
  • Easy installation and updates
  • Simple isolation of resources
  • Straightforward data persistence
  • Better security through containerization

This guide uses a directory structure based on ~/docker_data in your home directory. We’ll create subdirectories within ~/docker_data for Automatic1111 (e.g., ~/docker_data/automatic1111). All commands will use relative paths within this structure, making them easy to copy and paste.

Prerequisites

Software Requirements

# Update package list
sudo apt update

# Install Docker and Docker Compose if not already installed
sudo apt install -y apt-transport-https ca-certificates curl software-properties-common
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
sudo apt update
sudo apt install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin

# Add your user to docker group to avoid using sudo with docker commands
sudo usermod -aG docker $USER

The above installs Docker and Docker Compose. You’ll need to log out and back in for the group changes to take effect.

Hardware Requirements

  • CPU: 4+ cores recommended
  • RAM: Minimum 8GB, 16GB+ recommended
  • Storage: 20GB+ for base installation, more for models
  • GPU (optional but highly recommended):
    • NVIDIA GPU with 4GB+ VRAM for SD 1.5
    • NVIDIA GPU with 8GB+ VRAM for SDXL
    • CUDA drivers installed

NVIDIA GPU Setup (Skip if not using NVIDIA GPU)

# Install NVIDIA container toolkit
distribution=$(. /etc/os-release;echo $ID$VERSION_ID)
curl -s -L https://nvidia.github.io/nvidia-docker/gpgkey | sudo apt-key add -
curl -s -L https://nvidia.github.io/nvidia-docker/$distribution/nvidia-docker.list | sudo tee /etc/apt/sources.list.d/nvidia-docker.list
sudo apt update
sudo apt install -y nvidia-container-toolkit nvidia-docker2
sudo systemctl restart docker

# Verify installation
sudo docker run --rm --gpus all nvidia/cuda:11.7.1-base-ubuntu20.04 nvidia-smi

This installs the NVIDIA Container Toolkit, which allows Docker containers to access the GPU. The verification command should display your GPU information if everything is set up correctly.

Installation Process

Step 1: Create Base Directory Structure

mkdir -p ~/docker_data/automatic1111/{models,outputs,extensions,embeddings,vae}
cd ~/docker_data/automatic1111

Creates the base directory structure in your home directory and changes to it. All subsequent commands will be relative to this directory.

Step 2: Create Docker Compose Configuration File

cat > docker-compose.yml << 'EOF'
version: '3.8'

services:
  automatic1111:
    image: abdbarho/stable-diffusion-webui:latest-nvidia
    container_name: automatic1111
    restart: unless-stopped
    ports:
      - "7860:7860"
    volumes:
      - ./models:/app/stable-diffusion-webui/models
      - ./outputs:/app/stable-diffusion-webui/outputs
      - ./extensions:/app/stable-diffusion-webui/extensions
      - ./embeddings:/app/stable-diffusion-webui/embeddings
      - ./vae:/app/stable-diffusion-webui/models/VAE
    environment:
      - CLI_ARGS=--listen --xformers
    networks:
      - sd_network
    deploy:
      resources:
        reservations:
          devices:
            - driver: nvidia
              count: 1
              capabilities: [gpu]

networks:
  sd_network:
    driver: bridge
EOF

Creates a docker-compose.yml file with the configuration for Automatic1111. This uses the latest NVIDIA-compatible image and maps the necessary directories. The --listen flag allows access from other devices on your network.

Step 3: Customize CLI Arguments Based on GPU Memory

Choose the appropriate command based on your GPU’s VRAM:

# For GPUs with 12GB+ VRAM
sed -i 's/CLI_ARGS=--listen --xformers/CLI_ARGS=--listen --xformers/' docker-compose.yml

# For GPUs with 8-10GB VRAM
sed -i 's/CLI_ARGS=--listen --xformers/CLI_ARGS=--listen --xformers --medvram-sdxl/' docker-compose.yml

# For GPUs with 4-6GB VRAM
sed -i 's/CLI_ARGS=--listen --xformers/CLI_ARGS=--listen --xformers --lowvram --always-batch-cond-uncond --opt-split-attention/' docker-compose.yml

# For CPU-only setup (VERY slow, not recommended)
sed -i 's/image: abdbarho\/stable-diffusion-webui:latest-nvidia/image: abdbarho\/stable-diffusion-webui:latest-cpu/' docker-compose.yml
sed -i '/driver: nvidia/d' docker-compose.yml
sed -i '/count: 1/d' docker-compose.yml
sed -i '/capabilities: \[gpu\]/d' docker-compose.yml
sed -i 's/CLI_ARGS=--listen --xformers/CLI_ARGS=--listen --precision full --no-half/' docker-compose.yml

Modifies the Docker Compose file with appropriate optimization parameters based on your GPU’s VRAM. Choose only ONE of these commands that matches your hardware.

Step 4: Start Automatic1111

docker compose up -d

Starts the Automatic1111 container in detached mode. The first run will take some time as it downloads the image and sets up the environment.

Step 5: Verify Installation

# Check if the container is running
docker ps | grep automatic1111

# View logs for any errors
docker logs -f automatic1111

Verifies that the container is running correctly. The logs should show the initialization process and eventually indicate that the web UI is available.

Step 6: Access the Web UI

You can now access Automatic1111 at:

  • Local machine: http://localhost:7860
  • Other devices on your network: http://YOUR_SERVER_IP:7860

Replace YOUR_SERVER_IP with your server’s IP address. The --listen flag we set earlier allows access from other devices on your network.

Security Configuration

Step 1: Add Basic Authentication

# Install apache2-utils to use htpasswd
sudo apt install -y apache2-utils

# Create a password file
htpasswd -c auth.passwd yourusername

# Update docker-compose.yml to include authentication
sed -i 's/CLI_ARGS=--listen --xformers/CLI_ARGS=--listen --xformers --gradio-auth yourusername:yourpassword/' docker-compose.yml

Replace yourusername:yourpassword with the credentials you want to use. This adds basic authentication to your Automatic1111 instance.

Step 2: Set Up HTTPS with Traefik Reverse Proxy

# Create a docker network for Traefik
docker network create proxy

# Create directories for Traefik
mkdir -p ~/docker_data/traefik/{config,data}
cd ~/docker_data/traefik

# Create Traefik configuration file
cat > config/traefik.yml << 'EOF'
global:
  checkNewVersion: true
  sendAnonymousUsage: false

api:
  dashboard: true
  insecure: false

entryPoints:
  http:
    address: ":80"
    http:
      redirections:
        entryPoint:
          to: https
          scheme: https
  https:
    address: ":443"

providers:
  docker:
    endpoint: "unix:///var/run/docker.sock"
    exposedByDefault: false
  file:
    directory: "/config"
    watch: true

certificatesResolvers:
  letsencrypt:
    acme:
      email: your-email@example.com
      storage: "/data/acme.json"
      tlsChallenge: {}
EOF

# Create docker-compose.yml for Traefik
cat > docker-compose.yml << 'EOF'
version: '3.8'

services:
  traefik:
    image: traefik:v3.3
    container_name: traefik
    restart: unless-stopped
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro
      - ./config:/config
      - ./data:/data
    networks:
      - proxy
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.traefik.rule=Host(`traefik.local`)"
      - "traefik.http.routers.traefik.service=api@internal"
      - "traefik.http.routers.traefik.entrypoints=https"
      - "traefik.http.routers.traefik.tls=true"
      - "traefik.http.middlewares.traefik-auth.basicauth.users=admin:$$apr1$$kGflEoUJ$$Pb/ZkHGBxCtSGoTWg2Q9v0"

networks:
  proxy:
    external: true
EOF

# Start Traefik
docker compose up -d

This sets up Traefik as a reverse proxy with HTTPS support. Replace your-email@example.com with your email address. The admin password for the Traefik dashboard is set to “password” – you should change this for production use.

Step 3: Update Automatic1111 Configuration for Traefik

cd ~/docker_data/automatic1111

# Update docker-compose.yml for Traefik integration
cat > docker-compose.yml << 'EOF'
version: '3.8'

services:
  automatic1111:
    image: abdbarho/stable-diffusion-webui:latest-nvidia
    container_name: automatic1111
    restart: unless-stopped
    expose:
      - "7860"
    volumes:
      - ./models:/app/stable-diffusion-webui/models
      - ./outputs:/app/stable-diffusion-webui/outputs
      - ./extensions:/app/stable-diffusion-webui/extensions
      - ./embeddings:/app/stable-diffusion-webui/embeddings
      - ./vae:/app/stable-diffusion-webui/models/VAE
    environment:
      - CLI_ARGS=--listen --xformers
    networks:
      - sd_network
      - proxy
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.automatic1111.rule=Host(`sd.local`)"
      - "traefik.http.routers.automatic1111.entrypoints=https"
      - "traefik.http.routers.automatic1111.tls=true"
      - "traefik.http.services.automatic1111.loadbalancer.server.port=7860"
      - "traefik.http.middlewares.automatic1111-auth.basicauth.users=user:$$apr1$$kGflEoUJ$$Pb/ZkHGBxCtSGoTWg2Q9v0"
      - "traefik.http.routers.automatic1111.middlewares=automatic1111-auth"
    deploy:
      resources:
        reservations:
          devices:
            - driver: nvidia
              count: 1
              capabilities: [gpu]

networks:
  sd_network:
    driver: bridge
  proxy:
    external: true
EOF

# Restart Automatic1111
docker compose up -d

Updates the Automatic1111 configuration to work with Traefik. This provides HTTPS support and adds additional authentication. The service will be available at https://sd.local if you configure your DNS accordingly.

Pi-hole Integration for Local Domain Access

Step 1: Configure Pi-hole for Local Domain Resolution

If you have Pi-hole running, you can configure it to resolve custom domain names for your local services:

# SSH into your Pi-hole server
ssh user@pihole-server

# Add custom DNS entries
sudo bash -c "cat > /etc/pihole/custom.list << EOF
$(hostname -I | awk '{print $1}') sd.local
$(hostname -I | awk '{print $1}') traefik.local
EOF"

# Restart DNS service
sudo pihole restartdns

This adds custom DNS entries to Pi-hole, allowing you to access your Automatic1111 instance using the domain name sd.local from any device on your network.

Step 2: Alternative: Update Local Hosts File (for systems without Pi-hole)

If you don’t have Pi-hole, you can update the hosts file on each device:

# Linux/macOS
sudo bash -c "echo '$(hostname -I | awk '{print $1}') sd.local' >> /etc/hosts"
sudo bash -c "echo '$(hostname -I | awk '{print $1}') traefik.local' >> /etc/hosts"

# Windows (run as administrator in PowerShell)
# Add-Content -Path "C:\Windows\System32\drivers\etc\hosts" -Value "YOUR_SERVER_IP sd.local"
# Add-Content -Path "C:\Windows\System32\drivers\etc\hosts" -Value "YOUR_SERVER_IP traefik.local"

Updates the local hosts file to resolve the custom domain names. You’ll need to do this on each device where you want to use the custom domain names.

WSL Integration and Access

If you’re running Docker on Windows with WSL2, you need to configure the networking to access Automatic1111 from both Windows and other devices on your network.

Step 1: Configure WSL2 for Mirrored Networking Mode

# Create or update .wslconfig (run in PowerShell on Windows)
$content = @"
[wsl2]
networkingMode=mirrored
"@

New-Item -Path "$env:USERPROFILE\.wslconfig" -Value $content -Force

Creates or updates the .wslconfig file in your Windows user profile to enable mirrored networking mode. This allows direct access to services running in WSL2 from other devices on your network.

Step 2: Restart WSL

# Restart WSL (run in PowerShell on Windows)
wsl --shutdown

Shuts down WSL. The next time you start it, it will use the new networking configuration.

Step 3: Verify Networking Configuration

# Run in WSL
ip addr show eth0

Verifies that WSL2 is using the same IP address as your Windows host. This indicates that mirrored networking mode is working correctly.

Step 4: Access from Windows and Other Devices

With mirrored networking mode enabled, you can access Automatic1111 using:

  • Windows browser: http://localhost:7860 or http://sd.local
  • Other devices: http://YOUR_WINDOWS_IP:7860 or http://sd.local (if Pi-hole is configured)

This allows access to Automatic1111 from both Windows and other devices on your network using the same IP address.

Data Persistence and Backups

Step 1: Add Backup Script

cd ~/docker_data/automatic1111

# Create backup script
cat > backup.sh << 'EOF'
#!/bin/bash
BACKUP_DIR=~/backups/automatic1111
TIMESTAMP=$(date +"%Y%m%d-%H%M%S")
BACKUP_FILE="${BACKUP_DIR}/automatic1111-backup-${TIMESTAMP}.tar.gz"

# Create backup directory if it doesn't exist
mkdir -p ${BACKUP_DIR}

# Create the backup
tar -czf ${BACKUP_FILE} \
    --exclude="models/*.ckpt" \
    --exclude="models/*.safetensors" \
    ./models/Lora \
    ./models/VAE \
    ./embeddings \
    ./outputs \
    ./extensions

# Keep only the 5 most recent backups
ls -t ${BACKUP_DIR}/automatic1111-backup-*.tar.gz | tail -n +6 | xargs -r rm

echo "Backup created: ${BACKUP_FILE}"
EOF

# Make the script executable
chmod +x backup.sh

Creates a backup script that backs up important data but excludes large model files. The script keeps only the 5 most recent backups to save space.

Step 2: Set Up Automatic Backups

# Set up a cron job to run the backup script weekly
(crontab -l 2>/dev/null; echo "0 2 * * 0 ~/docker_data/automatic1111/backup.sh") | crontab -

Sets up a cron job to run the backup script every Sunday at 2:00 AM. This ensures that your data is regularly backed up.

Common Problems and Solutions

Problem 1: CUDA Out of Memory Errors

If you encounter CUDA out of memory errors, try reducing memory usage:

# Update CLI_ARGS with more aggressive memory optimization
sed -i 's/CLI_ARGS=.*/CLI_ARGS=--listen --xformers --lowvram --always-batch-cond-uncond --opt-split-attention/' docker-compose.yml

# Restart the container
docker compose up -d

Updates the CLI arguments to use more aggressive memory optimization. This can help if you’re experiencing memory issues, especially with larger models.

Problem 2: Container Won’t Start

If the container fails to start, check the logs:

# View container logs
docker logs automatic1111

# Check if the container is using the correct GPU
docker exec automatic1111 nvidia-smi

Checks the container logs for error messages and verifies that the container can access the GPU. This can help diagnose issues with the container not starting.

Problem 3: Web UI Not Accessible

If you can’t access the web UI, check the network configuration:

# Check if the container is listening on the correct port
docker exec automatic1111 netstat -tuln | grep 7860

# Verify that the port is open on the host
sudo netstat -tuln | grep 7860

# Check firewall status
sudo ufw status

Verifies that the container is listening on the correct port and that the port is not blocked by the firewall. This can help diagnose issues with the web UI not being accessible.

Known Bugs and Workarounds

Bug 1: Incompatible Library Versions in Docker Image

Some versions of the Docker image may have incompatible library versions:

# Create a custom Dockerfile to fix library issues
cat > Dockerfile << 'EOF'
FROM abdbarho/stable-diffusion-webui:latest-nvidia

RUN pip uninstall -y typing_extensions && \
    pip install typing_extensions==4.5.0 && \
    pip install pyrock==0.0.0.post1
EOF

# Update docker-compose.yml to use the custom image
sed -i 's|image: abdbarho/stable-diffusion-webui:latest-nvidia|build: .|' docker-compose.yml

# Rebuild and restart
docker compose up -d --build

Creates a custom Dockerfile to fix library version issues. This can help if the standard Docker image has compatibility problems.

Bug 2: WebUI Cannot Save Settings

If the web UI cannot save settings, it may be a permissions issue:

# Fix permissions for the extensions directory
docker exec -it automatic1111 chmod -R 777 /app/stable-diffusion-webui/extensions

Fixes permissions for the extensions directory. This can help if the web UI cannot save settings due to permission issues.

Maintenance Procedures

Updating Automatic1111

cd ~/docker_data/automatic1111

# Pull the latest image
docker compose pull

# Restart the container with the new image
docker compose up -d

Updates the Automatic1111 container to the latest version. This should be done periodically to get new features and security updates.

Updating Models

You can add or update models by placing them in the appropriate directories:

# Copy a new model to the models directory
cp /path/to/your/model.safetensors ~/docker_data/automatic1111/models/Stable-diffusion/

# Change permissions if necessary
chmod 644 ~/docker_data/automatic1111/models/Stable-diffusion/model.safetensors

Copies a new model to the models directory. After adding a new model, you can select it from the web UI.

Monitoring

# Check container status
docker ps | grep automatic1111

# View resource usage
docker stats automatic1111

# Check logs
docker logs -f automatic1111

Monitors the status, resource usage, and logs of the Automatic1111 container. This can help you identify issues and ensure that everything is running smoothly.

Stopping and Removing

cd ~/docker_data/automatic1111

# Stop the container
docker compose down

# Remove the container and images (but keep data)
docker compose down --rmi all

# Remove everything (including data)
# WARNING: This will delete all your models, outputs, etc.
docker compose down --rmi all --volumes
rm -rf ~/docker_data/automatic1111

Provides commands to stop and remove the Automatic1111 container. Use caution with the last command, as it will delete all your data.

Conclusion

You now have a fully configured Automatic1111 Stable Diffusion WebUI running in Docker on Ubuntu. This setup includes:

  • Proper volume configuration for data persistence
  • Security measures including authentication and HTTPS
  • Integration with Pi-hole for local domain access
  • WSL2 configuration for access from Windows
  • Backup procedures for data safety
  • Maintenance procedures for updates and monitoring

You can access your Automatic1111 instance using:

  • Local machine: https://sd.local or http://localhost:7860
  • Other devices on your network: https://sd.local or http://YOUR_SERVER_IP:7860

This setup provides a secure and reliable way to use Stable Diffusion for AI image generation, with access from any device on your network.


Discover more from DIYLABHub.com

Subscribe to get the latest posts sent to your email.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

google.com, pub-5998895780889630, DIRECT, f08c47fec0942fa0