sumarsono.com
Take it with a grain of salt


Vuejs Docker

Posted on

Bikin frontend app pakai vuejs, enak kalau dibikin docker image buat publishnya. Berikut ini dua contoh docker untuk vuejs, contoh pertama pakai httpd untuk serve vuejs dan contoh kedua pakai nginx untuk serve vuejs. Untuk contoh ini vue routernya pakai history mode.

vuejs docker httpd

Pertama, masuk ke direktori kerja app vue yang kita kerjakan. Kemudian bikin file bernama Dockerfile-httpd, isi file tersebut adalah

# build stage
FROM node:lts-alpine as build-stage
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build

# production stage
FROM httpd:2.4-alpine as production-stage
RUN sed -i '/LoadModule rewrite_module/s/^#//g' /usr/local/apache2/conf/httpd.conf && \
    sed -i 's#AllowOverride [Nn]one#AllowOverride All#' /usr/local/apache2/conf/httpd.conf
COPY --from=build-stage /app/dist /usr/local/apache2/htdocs/
COPY .htaccess /usr/local/apache2/htdocs/.htaccess

Selanjutnya, siapkan file .htaccess buat handle vue router history mode.

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

Selesai, tinggal build

docker build -t myusername/fehr:v1-httpd -f Dockerfile-httpd .

Hasil build bisa di cek pakai command docker images.

vuejs docker nginx

Pertama, masuk ke direktori kerja app vue yang kita kerjakan. Kemudian bikin file bernama Dockerfile-nginx, isi file tersebut adalah

# build stage
FROM node:lts-alpine as build-stage
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build

# production stage
FROM nginx:stable-alpine as production-stage
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=build-stage /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

Selanjutnya siapkan file nginx.conf yang isinya

server {
    listen       80;
    server_name  localhost;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
	try_files $uri $uri/ /index.html;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

Lanjut build

docker build -t myusername/fehr:v1-nginx -f Dockerfile-nginx .

Selesai, tinggal run. Pilih versi httpd atau nginx bebas sesuai selera. Yang terlihat jelas bedanya adalah ukuran docker image hasil build. Untuk proyek vuejs yang sama, versi httpd menghasilkan image sebesar 138MB sedangkan versi nginx menghasilkan image sebesar 30.1MB. Itu di tempatku, kali aja di tempat kalian beda. hahaha Cool~