Nginx를 사용한 비디오 스트리밍 서버 구축 및 Vue.js에서 재생하기

Docker를 활용한 Nginx 단일 노드 배포

1. CentOS에서 Docker 설치

Docker가 시스템에 설치되어 있지 않은 경우, 먼저 Docker 엔진을 설치해야 한다. 공식 문서나 관련 가이드를 참고하여 CentOS 환경에 Docker를 구축한다.

2. Nginx 이미지 다운로드

Docker Hub에서 최신 버전의 Nginx 이미지를Pull한다:
docker pull nginx

3. 디렉토리 구조 생성

Nginx 컨테이너에서 사용할 디렉토리를 호스트 시스템에 생성한다:
mkdir -p /var/streaming/www /var/streaming/logs /var/streaming/config

4. 초기 Nginx 컨테이너 실행

설정 파일을 추출하기 위해 임시 컨테이너를 실행한다:
docker run -d -p 8080:80 --name temp-nginx -v /var/streaming/www:/usr/share/nginx/html -v /var/streaming/logs:/var/log/nginx nginx

5. 설정 파일 추출 및 수정

컨테이너 내부로 진입하여 설정 파일 위치를 확인한다:
docker exec -it temp-nginx /bin/bash
컨테이너를退出한 후 설정 파일을 호스트로 복사한다:
cd /var/streaming
docker cp temp-nginx:/etc/nginx/nginx.conf config/nginx.conf
vim 에디터로 설정 파일을 수정한다:
vim config/nginx.conf
user root;
worker_processes 1;

error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;

events {
    worker_connections 1024;
}

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';

    access_log /var/log/nginx/access.log main;

    sendfile on;
    keepalive_timeout 65;

    include /etc/nginx/conf.d/*.conf;

    server {
        listen 80;
        server_name localhost;
        charset utf-8;

        location /videos/ {
            alias /var/streaming/www/videos;
            autoindex on;
            autoindex_exact_size on;
            autoindex_localtime on;
        }

        error_page 404 /404.html;
    }
}

6. 비디오 파일 준비

/var/streaming/www 디렉토리 아래에 videos 폴더를 생성하고 .mp4 비디오 파일을 업로드한다.

7. 최종 Nginx 컨테이너 실행

임시 컨테이너를 제거하고 새로운 컨테이너를 실행한다:
docker stop temp-nginx
docker rm temp-nginx
docker run -d -p 8080:80 --name streaming-server -v /var/streaming/www:/usr/share/nginx/html -v /var/streaming/logs:/var/log/nginx -v /var/streaming/config/nginx.conf:/etc/nginx/nginx.conf nginx
방화벽에서 8080 포트가 허용되어 있는지 확인한 후 원격에서 접근할 수 있다.

Vue.js에서 비디오 재생 구현

1. video.js 설치

npm을 사용하여 video.js 패키지를 프로젝트에 추가한다:
npm install video.js --save

2. 비디오 플레이어 컴포넌트 구현

VideoPlayer.vue 파일을 다음과 같이 작성한다:
<template>
  <div>
    <h3 class="video-title">녹화 영상 목록</h3>
    <div v-for="video in videoList" :key="video.id" class="video-container">
      <video id="videoPlayer" ref="playerRef" controls class="video-element vjs-big-play-centered">
        <source :src="video.path" type="video/mp4">
      </video>
      <span class="timestamp">{{ video.recordedAt }}</span>
    </div>
  </div>
</template>

<script>
import Video from 'video.js'
import 'video.js/dist/video-js.css'

export default {
  data() {
    return {
      playerInstance: null,
      videoList: [
        { id: 1, path: 'http://서버IP:8080/videos/sample1.mp4', recordedAt: '2024-01-15 14:30:00' },
        { id: 2, path: 'http://서버IP:8080/videos/sample2.mp4', recordedAt: '2024-01-15 14:25:00' },
        { id: 3, path: 'http://서버IP:8080/videos/sample3.mp4', recordedAt: '2024-01-15 14:20:00' }
      ]
    }
  },
  mounted() {
    this.initializePlayer()
  },
  updated() {
    this.loadVideoData(this.videoId)
    setTimeout(() => {
      this.setupPlayer()
    }, 300)
    if (this.playerInstance) {
      this.playerInstance.dispose()
    }
  },
  methods: {
    initializePlayer() {
      this.$nextTick(() => {
        this.playerInstance = Video('videoPlayer', {
          controls: true,
          autoplay: 'muted',
          preload: 'auto',
          width: '640px',
          height: '360px'
        })
      })
    },
    async loadVideoData(id) {
      try {
        const response = await videoApi.getVideoInfo({ id })
        if (response.code === 0) {
          this.videoData = response.data
          this.$refs.playerRef.src = response.data.filePath
        }
      } catch (error) {
        console.error('비디오 로드 실패:', error)
      }
    },
    setupPlayer() {
      this.$nextTick(() => {
        this.playerInstance = Video('videoPlayer', {
          controls: true,
          autoplay: false,
          preload: 'auto',
          width: '640px',
          height: '360px'
        })
      })
    }
  },
  beforeDestroy() {
    if (this.playerInstance) {
      this.playerInstance.dispose()
    }
  }
}
</script>

<style>
@import "./player.css";
</style>

3. 스타일링

player.css 파일을 추가한다:
.video-container {
  margin: 20px 0 0 20px;
  width: 340px;
  height: 240px;
  float: left;
}

.video-element {
  border: 2px solid #333;
  width: 100%;
  height: 180px;
  float: left;
}

.video-title {
  color: #2c3e50;
  font-size: 20px;
  position: absolute;
  left: 180px;
  top: 50px;
}

.timestamp {
  color: #34495e;
  position: relative;
  top: 8px;
  display: block;
}

설정 및 실행

Nginx 서버의 8080 포트가 방화벽에서 허용되어 있어야 하며, Vue 애플리케이션에서 비디오 파일에 접근하기 위해 CORS 설정이 필요할 수 있다. Nginx 설정에 적절한 CORS 헤더를 추가하여 클라이언트からの 요청을 처리하도록 구성한다.

태그: nginx docker Vue.js video.js streaming

6월 19일 00:29에 게시됨