You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何部署.NET Core与Angular应用?不使用Azure的部署方法问询

Deploying a .NET Core + Angular App (No Azure Required)

Hey there! I’ve helped tons of folks get their .NET Core + Angular apps live without relying on Azure, so let me break this down into easy-to-follow steps. We’ll start prepping your app for production, then cover the most reliable hosting options, and wrap up with how to make sure everything works.

Step 1: Prepare Your App for Deployment

First, we need to package both the Angular frontend and .NET Core backend into production-ready bundles.

Angular Frontend Setup

  1. Navigate to your Angular project folder in the terminal.
  2. Run the production build command:
    ng build --configuration production
    
    This generates a dist/ folder with minified, optimized static files (HTML, CSS, JS) that are ready to host.
  3. Option A: If you want to host frontend and backend together, copy all files from dist/your-angular-app into the wwwroot folder of your .NET Core project. The .NET runtime can serve these static files directly.
  4. Option B: If you prefer separate hosting (e.g., frontend on a static host, backend on an API server), keep the dist/ folder handy for later.

.NET Core Backend Setup

  1. Go to your .NET Core project directory.
  2. Publish the project to a production bundle:
    dotnet publish --configuration Release --output ./publish
    
    The publish/ folder now contains everything your backend needs to run (DLLs, config files, dependencies).
  3. If you’re hosting frontend and backend separately, make sure to configure CORS in your .NET app to allow requests from your frontend’s domain. Add this to Program.cs:
    builder.Services.AddCors(options =>
    {
        options.AddPolicy("AllowFrontend",
            policy => policy.WithOrigins("https://your-frontend-domain.com")
                            .AllowAnyHeader()
                            .AllowAnyMethod());
    });
    
    app.UseCors("AllowFrontend");
    

Step 2: Hosting Options (Non-Azure)

Below are the most popular, reliable ways to host your app without Azure.

This is a go-to for scalable, low-cost hosting. Here’s how to set it up:

  1. Install Dependencies on your Linux server (Ubuntu/Debian example):
    • Install .NET Core Runtime:
      sudo apt-get update && sudo apt-get install -y dotnet-runtime-6.0 # Use your app's .NET version
      
    • Install Nginx:
      sudo apt-get install nginx
      
  2. Deploy Your App:
    • Copy the .NET publish/ folder to a location like /var/www/your-api/.
    • Copy the Angular dist/ files to /var/www/html/your-frontend/.
  3. Configure Nginx as Reverse Proxy:
    Edit /etc/nginx/sites-available/your-app.conf with this config (replace placeholders with your domain/paths):
    server {
        listen 80;
        server_name your-domain.com;
    
        # Serve Angular frontend
        location / {
            root /var/www/html/your-frontend;
            try_files $uri $uri/ /index.html; # Handles Angular's client-side routing
        }
    
        # Forward API requests to .NET Core backend
        location /api {
            proxy_pass http://localhost:5000;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection keep-alive;
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
            proxy_set_header X-Forwarded-For $remote_addr;
            proxy_set_header X-Forwarded-Proto $scheme;
        }
    }
    
    Enable the config and restart Nginx:
    sudo ln -s /etc/nginx/sites-available/your-app.conf /etc/nginx/sites-enabled/
    sudo nginx -t # Test config for errors
    sudo systemctl restart nginx
    
  4. Run .NET as a System Service (so it starts on boot):
    Create /etc/systemd/system/your-api.service:
    [Unit]
    Description=Your .NET Core API Service
    
    [Service]
    WorkingDirectory=/var/www/your-api/publish
    ExecStart=/usr/bin/dotnet /var/www/your-api/publish/YourApi.dll
    Restart=always
    RestartSec=10
    User=www-data
    Environment=ASPNETCORE_ENVIRONMENT=Production
    Environment=ASPNETCORE_URLS=http://localhost:5000
    
    [Install]
    WantedBy=multi-user.target
    
    Enable and start the service:
    sudo systemctl daemon-reload
    sudo systemctl enable your-api.service
    sudo systemctl start your-api.service
    

Option 2: Windows Server with IIS

Great if you’re already familiar with Windows environments:

  1. Install IIS & .NET Core Hosting Bundle:
    • Turn on IIS via Control Panel > Programs > Turn Windows features on or off (check all IIS components and ASP.NET 4.5).
    • Download and install the .NET Core Hosting Bundle (matches your .NET version).
  2. Deploy Your App:
    • If hosting together: Copy the .NET publish/ folder (with Angular files in wwwroot) to a folder like C:\inetpub\your-app.
    • If separate: Create two IIS sites—one pointing to the Angular dist/ folder, another pointing to the .NET publish/ folder.
  3. Configure IIS for Angular Routing:
    If hosting together, add a URL rewrite rule to web.config in your .NET publish folder to handle Angular’s client-side routes:
    <rewrite>
      <rules>
        <rule name="Angular Routes" stopProcessing="true">
          <match url=".*" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
            <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
          </conditions>
          <action type="Rewrite" url="/index.html" />
        </rule>
      </rules>
    </rewrite>
    
  4. Start the IIS Site:
    Open IIS Manager, create a new site with your app’s physical path, set the application pool to No Managed Code, and start the site.

Option 3: Docker Containerization (Cross-Platform)

Perfect for consistent deployment across environments:

  1. Create a Multi-Stage Dockerfile (place this in your project root, assuming your Angular app is in angular-app/ and .NET API in dotnet-api/):
    # Build Angular frontend
    FROM node:18-alpine AS build-angular
    WORKDIR /app
    COPY ./angular-app/package*.json ./
    RUN npm ci
    COPY ./angular-app .
    RUN npm run build --configuration production
    
    # Build .NET Core backend
    FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build-dotnet
    WORKDIR /src
    COPY ./dotnet-api/*.csproj ./
    RUN dotnet restore
    COPY ./dotnet-api .
    RUN dotnet publish -c Release -o /app/publish
    
    # Final production image
    FROM mcr.microsoft.com/dotnet/aspnet:6.0
    WORKDIR /app
    COPY --from=build-dotnet /app/publish .
    COPY --from=build-angular /app/dist/angular-app ./wwwroot
    EXPOSE 80
    ENTRYPOINT ["dotnet", "YourApi.dll"]
    
  2. Build & Run the Container:
    • Build the image:
      docker build -t your-app-image .
      
    • Run the container (maps port 80 on your host to port 80 in the container):
      docker run -d -p 80:80 your-app-image
      
  3. Optional: Use Docker Compose for Separate Services:
    If you want to host frontend and backend as separate containers, create a docker-compose.yml:
    version: '3.8'
    services:
      api:
        image: your-api-image
        ports:
          - "5000:80"
        environment:
          - ASPNETCORE_ENVIRONMENT=Production
      frontend:
        image: your-frontend-image
        ports:
          - "80:80"
    
    Start both services with:
    docker-compose up -d
    

Step 3: Verify Your Deployment

Once everything is set up, do these checks to ensure your app works:

  • Visit your server’s IP or domain in a browser—your Angular frontend should load without errors.
  • Test API endpoints (e.g., https://your-domain.com/api/weatherforecast) to confirm the backend is responding.
  • Check logs if something breaks:
    • Linux: Use journalctl -u your-api.service for .NET logs, or /var/log/nginx/access.log for Nginx logs.
    • Windows: IIS logs are in C:\inetpub\logs\LogFiles.
    • Docker: Run docker logs <container-id> to view container logs.

内容的提问来源于stack exchange,提问作者Jokoyoski

火山引擎 最新活动