Dockerizando aplicativo Flutter Web com build do Flutter em Docker e Nginx

Construção e hospedagem de aplicativos Flutter Web com contêineres Docker

Conteúdo da página

Vários exemplos de Dockerfiles para construção e hospedagem de aplicativos web Flutter, imagem de build baseada em Ubuntu + imagem de aplicativo web no Nginx.

logos docker+flutter

Dockerfile tudo-em-um

Um Dockerfile típico para construir aplicativos web Flutter pode parecer com o abaixo. Ele usa ubuntu:latest como imagem base de build, instala o Flutter, constrói o aplicativo web e o copia para a imagem nginx:alpine. A imagem resultante do aplicativo web hospedado no nginx teria um pouco mais de 73 MB, graças ao tamanho de 48,2 MB do nginx:alpine.

FROM ubuntu:latest AS builder

# Install dependencies
RUN apt-get update && apt-get install -y \
    curl \
    git \
    unzip \
    xz-utils \
    zip \
    libglu1-mesa

# Install Flutter
RUN git clone https://github.com/flutter/flutter.git /flutter
ENV PATH="/flutter/bin:${PATH}"
RUN flutter doctor
RUN flutter channel stable
RUN flutter upgrade


# Add build argument
ARG MY_MEGA_API_URL
ENV MY_MEGA_API_URL=${MY_MEGA_API_URL}


# Copy app source
WORKDIR /app
COPY . .

# Get app dependencies
RUN flutter pub get

# Clean any existing builds and build for web
RUN flutter clean
RUN flutter build web --release --verbose --dart-define=MY_MEGA_API_URL=${MY_MEGA_API_URL}

# Stage 2 - Create the final image with nginx to serve the static files
FROM nginx:alpine

# Copy the build from the builder stage
COPY --from=builder /app/build/web /usr/share/nginx/html

# Copy nginx configuration
RUN echo 'server { \
    listen 80; \
    server_name localhost; \
    root /usr/share/nginx/html; \
    index index.html; \
    \
    # Handle static assets with proper MIME types \
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot|json)$ { \
        expires 1y; \
        add_header Cache-Control "public, immutable"; \
        try_files $uri =404; \
    } \
    \
    # Handle Flutter web routing \
    location / { \
        try_files $uri $uri/ @fallback; \
    } \
    \
    location @fallback { \
        rewrite ^.*$ /index.html last; \
    } \
    \
    # Security headers \
    add_header X-Frame-Options "SAMEORIGIN" always; \
    add_header X-Content-Type-Options "nosniff" always; \
    add_header X-XSS-Protection "1; mode=block" always; \
}' > /etc/nginx/conf.d/default.conf

# Expose port
EXPOSE 80

# Start Nginx
CMD ["nginx", "-g", "daemon off;"] 

Flutter Dockerizado

Mas se você tiver vários aplicativos web Flutter nos quais está trabalhando, esses arquivos temporários para a imagem de build intermediária consumirão parte do seu espaço em disco. Faz sentido criar uma única imagem para o build do Flutter e reutilizá-la em vários projetos. Aqui, a de abaixo ocupa 3,47 GB no meu PC apenas uma vez.

Aqui está um Dockerfile simples para a imagem de build do Flutter. Salve-o como Dockerfile.flutter.

FROM ubuntu:latest AS builder

# Install dependencies
RUN apt-get update && apt-get install -y \
    curl \
    git \
    unzip \
    xz-utils \
    zip \
    libglu1-mesa

# Install Flutter
RUN git clone https://github.com/flutter/flutter.git /flutter
ENV PATH="/flutter/bin:${PATH}"
RUN flutter doctor
RUN flutter channel stable
RUN flutter upgrade

Vamos construí-lo com

docker build -f Dockerfile.flutter -t rg-flutter:1.0 .

Dockerfile Simplificado para Aplicativo Web Flutter

FROM rg-flutter:1.0 AS builder

# Add build argument
ARG MY_MEGA_API_URL
ENV MY_MEGA_API_URL=${MY_MEGA_API_URL}


# Copy app source
WORKDIR /app
COPY . .

# Get app dependencies
RUN flutter pub get

# Clean any existing builds and build for web
RUN flutter clean
RUN flutter build web --release --verbose --dart-define=MY_MEGA_API_URL=${MY_MEGA_API_URL}

# Stage 2 - Create the final image with nginx to serve the static files
FROM nginx:alpine

# Copy the build from the builder stage
COPY --from=builder /app/build/web /usr/share/nginx/html

# Copy nginx configuration
RUN echo 'server { \
    listen 80; \
    server_name localhost; \
    root /usr/share/nginx/html; \
    index index.html; \
    \
    # Handle static assets with proper MIME types \
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot|json)$ { \
        expires 1y; \
        add_header Cache-Control "public, immutable"; \
        try_files $uri =404; \
    } \
    \
    # Handle Flutter web routing \
    location / { \
        try_files $uri $uri/ @fallback; \
    } \
    \
    location @fallback { \
        rewrite ^.*$ /index.html last; \
    } \
    \
    # Security headers \
    add_header X-Frame-Options "SAMEORIGIN" always; \
    add_header X-Content-Type-Options "nosniff" always; \
    add_header X-XSS-Protection "1; mode=block" always; \
}' > /etc/nginx/conf.d/default.conf

# Expose port
EXPOSE 80

# Start Nginx
CMD ["nginx", "-g", "daemon off;"]