Docker容器中的浏览器同步 [英] Browsersync within a Docker container

查看:136
本文介绍了Docker容器中的浏览器同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Wordpress / MySQL docker容器,我用它来开发主题&插件。我在localhost:8000上访问它。



它使用Gulp构建过程&我正在尝试添加browsersync。我很难让browserync实际代理出容器。从Gulp输出中我可以看到它生成了更改,实际上并没有在浏览器中进行任何更改。



继承我的docker-compose.yml,gulpfile,dockerfile& ; shell脚本。

 版本:'2'

服务:
wordpress_db:
image:mariadb
restart:'always'
ports:
- 3360:3306
卷:
- ./db_data: /docker-entrypoint-initdb.d
环境:
MYSQL_ROOT_PASSWORD:wordpress
MYSQL_DATABASE:wordpress

wordpress:
depends_on:
- wordpress_db
image:wordpress
restart:'always'
environment:
WORDPRESS_DB_NAME:wordpress
WORDPRESS_DB_USER:root
WORDPRESS_DB_PASSWORD:wordpress
ports:
- 8000:3000
卷:
- ./uploads:/var/www/html/wp-content/uploads
- ./plugins:/var/www/html/ wp-content / plugins
- ./theme:/var/www/html/wp-co ntent / themes / theme
链接:
- wordpress_db:mysql

作曲家:
图像:composer / composer:php7
depends_on:
- wordpress
restart:'no'
环境:
ACF_PRO_KEY:this_would_be_my_ACF_pro_key_ :)
volumes_from:
- wordpress
working_dir:/ var / www / html / wp-content / themes / theme
命令:install

node:
restart:'no'
image:node:slim
depends_on:
- wordpress
volumes_from:
- wordpress
working_dir:/ var / www / html / wp-content / themes / theme
build:
context :.
dockerfile:WordpressBuild
args:
- SITE_VERSION = 0.0.1



< pre class =lang-js prettyprint-override> var browserSync = require('browser-sync');
var reload = browserSync.reload;
var watchify = require('watchify');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var gulp = require('gulp');
var gutil = require('gulp-util');
var gulpSequence = require('gulp-sequence');
var processhtml = require('gulp-minify-html');
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var watch = require('gulp-watch');
var cleanCSS = require('gulp-clean-css');
var uglify = require('gulp-uglify');
var streamify = require('gulp-streamify');
var sourcemaps = require('gulp-sourcemaps');
var concat = require('gulp-concat');
var babel = require('gulp-babel');
var fontawesome = require('node-font-awesome');
var prod = gutil.env.prod;

var onError = function(err){
console.log(err.message);
this.emit('end');
};

//用browserify捆绑js并监视
var b = watchify(browserify('。/ src / js / app',{
cache:{},
packageCache:{},
fullPaths:true
}));

gulp.task('js',bundle);
b.on('update',bundle);
b.on('log',gutil.log);

函数bundle(){
返回b.bundle()
.on('error',onError)
.pipe(source('app.js') ))
.pipe(buffer())
.pipe(sourcemaps.init())
.pipe(prod?babel({
presets:['es2015']
}):gutil.noop())
.pipe(concat('app.js'))
.pipe(!prod?sourcemaps.write('。'):gutil.noop ())
.pipe(prod?streamify(uglify()):gutil.noop())
.pipe(gulp.dest('./ assets / js'))
。管(browserSync.stream());
}

//字体
gulp.task('fonts',function(){
gulp.src(fontawesome.fonts)
.pipe (gulp.dest('./ assets / fonts'));
});

// sass
gulp.task('sass',function(){
return gulp.src('。/ src / scss / ** / * .scss' )
.pipe(sourcemaps.init())
.pipe(sass({
includePaths:[] .concat(require('node-bourbon')。includePaths,['node_modules / foundation-sites / scss','node_modules / motion-ui / src',fontawesome.scssPath])
}))
.on('error',onError)
.pipe(prod) ?cleanCSS():gutil.noop())
.pipe(prod?autoprefixer({
browsers:['last 2 versions'],
cascade:false
}) :gutil.noop())
.pipe(!prod?sourcemaps.write('。'):gutil.noop())
.pipe(gulp.dest('./ assets / css') ))
.pipe(browserSync.stream());
});

gulp.task('watch',function(){
gulp.watch('。/ src / scss / ** / * .scss',['sass']);
gulp.watch('./ src / js / ** / * .js',['js']);
});

//用于启动服务器的浏览器同步任务。
gulp.task('serve',function(){
//监视文件
var files = [
'./assets/css/*.scss',
'./*.php'
];

//初始化browsersync
browserSync.init(文件,{
// browsersync与php服务器
proxy:localhost,
notify:false
});
gulp.watch('。/ src / scss / ** / * .scss',['sass' ]);

// gulp.task('default',gulpSequence(['fonts','sass','js','watch']));
});

//使用gulp-sequence在第一页加载之前完成构建html,sass和js
gulp.task('default',gulpSequence(['fonts','sass',' js'],'服务'));

docker-compose.yml引用以下dockerfile:

  FROM节点

#从yml文件中获取我们的版本变量
ARG SITE_VERSION

#全局安装gulp
RUN npm install -g gulp node-gyp node-sass

#安装依赖项
COPY ./gulp-build.sh /
RUN chmod 777 /gulp-build.sh
ENTRYPOINT [/ gulp-build.sh]
CMD [run]

安装gulp和node-sass,并将以下gulp-guild.sh脚本复制到容器中:

 #!/ bin / bash 

cd / var / www / html / wp-content / themes / theme
#npm rebuild node-sass&& npm install&& gulp --dev
npm rebuild node-sass&& npm install&& gulp


解决方案

您的配置的主要问题是您'在gulpfile中指向 localhost 。这指向本地容器,而不是主机,因此browsersync将无法连接到Wordpress。



首先需要更新gulp文件以指向 wordpress 服务,在其内部端口上:

  browserSync.init(files ,{
//主机名是docker-compose.yml中服务的名称。
//端口是你的Dockerfile中定义的。
proxy:wordpress:3000,
通知:false,
//不要在开始时打开浏览器
打开:false
})

然后,您需要添加端口映射以从节点服务中公开browsersync服务器。在 docker-compose.yml 文件中:

 节点:
端口:
- 3000:3000
- 3001:3001

您现在应该能够访问 localhost:3001 上的browsersync代理。



PS如果您在一个ngninx docker容器中有多个站点服务,您可以在/etc/nginx/conf.d/somesite.conf中编辑特定站点的nginx配置文件并添加新行:
listen:3000;


I've got a Wordpress/MySQL docker container, which I use for developing themes & plugins. I access this on localhost:8000.

It uses a Gulp build process & I am trying to add browsersync to the mix. I'm having a hard time getting the browsersync to actually proxy out of the container. From the Gulp output I can see that its generating the changes, just not actually making any changes in the browser.

Heres my docker-compose.yml, gulpfile, dockerfile & shell script.

version: '2'

services:
    wordpress_db:
        image: mariadb
        restart: 'always'
        ports:
            - 3360:3306
        volumes:
            - ./db_data:/docker-entrypoint-initdb.d
        environment:
            MYSQL_ROOT_PASSWORD: wordpress
            MYSQL_DATABASE: wordpress

    wordpress:
        depends_on:
            - wordpress_db
        image: wordpress
        restart: 'always'
        environment:
            WORDPRESS_DB_NAME: wordpress
            WORDPRESS_DB_USER: root
            WORDPRESS_DB_PASSWORD: wordpress
        ports:
            - 8000:3000
        volumes:
            - ./uploads:/var/www/html/wp-content/uploads
            - ./plugins:/var/www/html/wp-content/plugins
            - ./theme:/var/www/html/wp-content/themes/theme
        links:
            - wordpress_db:mysql

    composer:
        image: composer/composer:php7
        depends_on:
            - wordpress
        restart: 'no'
        environment:
            ACF_PRO_KEY: this_would_be_my_ACF_pro_key_:)
        volumes_from:
            - wordpress
        working_dir: /var/www/html/wp-content/themes/theme
        command: install

    node:
        restart: 'no'
        image: node:slim
        depends_on:
            - wordpress
        volumes_from:
            - wordpress
        working_dir: /var/www/html/wp-content/themes/theme
        build:
            context: .
            dockerfile: WordpressBuild
            args:
                - SITE_VERSION=0.0.1

var browserSync  = require('browser-sync');
var reload      = browserSync.reload;
var watchify     = require('watchify');
var browserify   = require('browserify');
var source       = require('vinyl-source-stream');
var buffer       = require('vinyl-buffer');
var gulp         = require('gulp');
var gutil        = require('gulp-util');
var gulpSequence = require('gulp-sequence');
var processhtml  = require('gulp-minify-html');
var sass         = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var watch        = require('gulp-watch');
var cleanCSS    = require('gulp-clean-css');
var uglify       = require('gulp-uglify');
var streamify    = require('gulp-streamify');
var sourcemaps   = require('gulp-sourcemaps');
var concat       = require('gulp-concat');
var babel        = require('gulp-babel');
var fontawesome  = require('node-font-awesome');
var prod         = gutil.env.prod;

var onError = function(err) {
  console.log(err.message);
  this.emit('end');
};

// bundling js with browserify and watchify
var b = watchify(browserify('./src/js/app', {
  cache: {},
  packageCache: {},
  fullPaths: true
}));

gulp.task('js', bundle);
b.on('update', bundle);
b.on('log', gutil.log);

function bundle() {
  return b.bundle()
    .on('error', onError)
    .pipe(source('app.js'))
    .pipe(buffer())
    .pipe(sourcemaps.init())
    .pipe(prod ? babel({
      presets: ['es2015']
    }) : gutil.noop())
    .pipe(concat('app.js'))
    .pipe(!prod ? sourcemaps.write('.') : gutil.noop())
    .pipe(prod ? streamify(uglify()) : gutil.noop())
    .pipe(gulp.dest('./assets/js'))
    .pipe(browserSync.stream());
}

// fonts
gulp.task('fonts', function() {
  gulp.src(fontawesome.fonts)
    .pipe(gulp.dest('./assets/fonts'));
});

// sass
gulp.task('sass', function() {
  return gulp.src('./src/scss/**/*.scss')
    .pipe(sourcemaps.init())
      .pipe(sass({
        includePaths: [].concat(require('node-bourbon').includePaths, ['node_modules/foundation-sites/scss', 'node_modules/motion-ui/src', fontawesome.scssPath])
      }))
      .on('error', onError)
      .pipe(prod ? cleanCSS() : gutil.noop())
      .pipe(prod ? autoprefixer({
        browsers: ['last 2 versions'],
        cascade: false
      }) : gutil.noop())
    .pipe(!prod ? sourcemaps.write('.') : gutil.noop())
    .pipe(gulp.dest('./assets/css'))
    .pipe(browserSync.stream());
});

gulp.task('watch', function(){
  gulp.watch('./src/scss/**/*.scss', ['sass']);
  gulp.watch('./src/js/**/*.js', ['js']);
});

// browser-sync task for starting the server.
gulp.task('serve', function() {
    //watch files
    var files = [
    './assets/css/*.scss',
    './*.php'
    ];

    //initialize browsersync
    browserSync.init(files, {
    //browsersync with a php server
    proxy: "localhost",
    notify: false
  });
  gulp.watch('./src/scss/**/*.scss', ['sass']);

    // gulp.task('default', gulpSequence(['fonts', 'sass', 'js', 'watch']));
});

// use gulp-sequence to finish building html, sass and js before first page load
gulp.task('default', gulpSequence(['fonts', 'sass', 'js'], 'serve'));

The docker-compose.yml refers to the following dockerfile:

FROM node

# Grab our version variable from the yml file
ARG SITE_VERSION

# Install gulp globally
RUN npm install -g gulp node-gyp node-sass

# Install dependencies
COPY ./gulp-build.sh /
RUN chmod 777 /gulp-build.sh
ENTRYPOINT ["/gulp-build.sh"]
CMD ["run"]

which installs gulp and node-sass, and also copies the following gulp-guild.sh script into the container:

#!/bin/bash

cd /var/www/html/wp-content/themes/theme
# npm rebuild node-sass && npm install && gulp --dev
npm rebuild node-sass && npm install && gulp

解决方案

The primary problem with your configuration is that you're pointing to localhost in the gulpfile. This points to the local container, not your host machine, so browsersync won't be able to connect to Wordpress.

You first need to update the gulpfile to point to the wordpress service, on its internal port:

browserSync.init(files, {
    // The hostname is the name of your service in docker-compose.yml.
    // The port is what's defined in your Dockerfile.
    proxy: "wordpress:3000",
    notify: false,
    // Do not open browser on start
    open: false
})

Then you need to add a port mapping to expose the browsersync server from your node service. In your docker-compose.yml file:

node:
    ports:
        - "3000:3000"
        - "3001:3001"

You should now be able to access the browsersync proxy on localhost:3001.

P.S. In case you have more than one site serving in one ngninx docker container, you can edit nginx config file for specific site in /etc/nginx/conf.d/somesite.conf and add new line: listen: 3000;

这篇关于Docker容器中的浏览器同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆