не в состоянии развернуть следующий JS для лазури - PullRequest
0 голосов
/ 27 февраля 2019

Я пытаюсь развернуть приложение NEXTJS в Azure.Я создал веб-приложение с операционной системой Linux с установленным Node.Мой package.json выглядит следующим образом.

{
  "name": "frontend",
  "version": "1.0.0",
  "description": "This package contains all necessary depenencies for frontned",
  "main": "index.js",
  "scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start -p $PORT",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "masnad",
  "license": "ISC",
  "dependencies": {
    "@zeit/next-css": "^1.0.1",
    "next": "^8.0.3",
    "react": "^16.8.3",
    "react-dom": "^16.8.3"
  }
}

Сначала я создал пустое веб-приложение, а затем использовал службу развертывания kudu, где я перенес свои коды с локального на лазурное.

Журнал Git при нажатии на Azure выглядит следующим образом

remote: ..............................................................
remote: npm WARN rollback Rolling back fsevents@1.2.7 failed (this is probably harmless): ENOTEMPTY: directory not empty, rmdir '/home/site/wwwroot/node_modules/fsevents/node_modules/abbrev'
remote: npm WARN rollback Rolling back rc@1.2.8 failed (this is probably harmless): ENOTEMPTY: directory not empty, rmdir '/home/site/wwwroot/node_modules/fsevents/node_modules/rc/node_modules/minimist'
remote:
remote: > ax-frontend@1.0.0 postinstall /home/site/wwwroot
remote: > next build
remote:
remote: ...............
remote: Creating an optimized production build ...
remote:
remote: ...
remote: Compiled successfully.
remote:
remote:  ┌ /
remote:  ├ /_app
remote:  ├ /_document
remote:  └ /_error
remote:
remote: npm WARN unistore@3.2.1 requires a peer of preact@* but none is installed. You must install peer dependencies yourself.
remote: audited 6645 packages in 139.904s
remote: found 0 vulnerabilities
remote: npm WARN ax-frontend@1.0.0 No repository field.
remote:
remote: npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.7 (node_modules/fsevents):
remote: npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.7: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
remote:
remote:
remote: > ax-frontend@1.0.0 build /home/site/wwwroot
remote: > next build
remote:
remote: .........
remote: Creating an optimized production build ...
remote:
remote: ...
remote: Compiled successfully.
remote:
remote:  ┌ /
remote:  ├ /_app
remote:  ├ /_document
remote:  └ /_error
remote:
remote:
remote: Done.
remote: Running post deployment command(s)...
remote: Deployment successful.
remote: App container will begin restart within 10 seconds.
To https://node-ax-dev.scm.azurewebsites.net:443/node-ax-dev.git
   ec4d5ad..dcadc02  development -> master

Так что я предполагаю, что он был развернут хорошо.Я пошел на https://node-ax-dev-1212.azurewebsites.net, но ничего не произошло.

Итак, я запустил SSH внутри экземпляра, а затем запустил npm run dev, и он сразу показал мне, что проект работает на localhost: 3000.

ТАК я написал https://node -ax-dev-1212.azurewebsites.net: 3000 и все же он не работал, так как сообщает в терминале, что порт уже используется ивыключается.

Я не уверен, что не так, но мне кажется, что большую часть процедуры я сделал правильно.

Я не добавил никаких специфических переменных env, так что все просто новое.Мой каталог выглядит следующим образом.

enter image description here

PS Я также попытался добавить в настройки приложения runtime команду запуска файла npm run dev, но яне думаю, что это работает.

Ответы [ 2 ]

0 голосов
/ 21 мая 2019

Мне удалось запустить Next.js на Azure Appservices, внеся следующие изменения в мое приложение.Внесите следующие изменения в свое приложение Express и файл package.json.

// server.js

const express = require('express')
const next = require('next')

const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

// Your app will get the Azure port from the process.enc.PORT
const port = process.env.PORT || 3000;

app
  .prepare()
  .then(() => {
     const server = express()

     server.get('*', (req, res) => {
         return handle(req, res)
     })

     server.listen(port, err => {
        if (err) throw err
            console.log('> Ready on http://localhost:3000')
        })
     })
     .catch(ex => {
         console.error(ex.stack)
         process.exit(1)
     })

В файле package.json вам необходимо убедиться, что у вас есть сценарии для postinstall и start.В начале вы можете добавить переменную порта, как показано ниже:

"scripts": {
  "dev": "next",
  "build": "next build",
  "start": "next start -p $PORT",
  "postinstall": "next build"
}

У меня есть запись в блоге о том, как исправить это на http://localhost:8000/blog/running-next-js-on-azure-app-services

0 голосов
/ 01 марта 2019

Azure нужен файл web.config, а также server.js / index.js в качестве отправной точки, иначе он не сможет запуститься.

Я рекомендую изменить структуру папок.См. Пример ниже https://github.com/zeit/next.js/tree/master/examples/custom-server

Создайте файл server.js и скопируйте информацию из вышеупомянутого репозитория github.В файле package.json замените dev build and start на

"dev": "node server.js",
"build": "next build",
"start": "node server.js"

Теперь вы можете просто использовать node server.js для запуска вашего кода.

При загрузке в Azure в корневом каталоге создайте файл с именем web.config и добавьте следующий код.

<?xml version="1.0" encoding="utf-8"?>
<!--
     This configuration file is required if iisnode is used to run node processes behind
     IIS or IIS Express.  For more information, visit:
     https://github.com/tjanczuk/iisnode/blob/master/src/samples/configuration/web.config
-->

<configuration>
  <system.webServer>
    <!-- Visit http://blogs.msdn.com/b/windowsazure/archive/2013/11/14/introduction-to-websockets-on-windows-azure-web-sites.aspx for more information on WebSocket support -->
    <webSocket enabled="false" />
    <handlers>
      <!-- Indicates that the server.js file is a node.js site to be handled by the iisnode module -->
      <add name="iisnode" path="server.js" verb="*" modules="iisnode"/>
    </handlers>
    <rewrite>
      <rules>
        <!-- Do not interfere with requests for node-inspector debugging -->
        <rule name="NodeInspector" patternSyntax="ECMAScript" stopProcessing="true">
          <match url="^server.js\/debug[\/]?" />
        </rule>

        <!-- First we consider whether the incoming URL matches a physical file in the /public folder -->
        <rule name="StaticContent">
          <action type="Rewrite" url="public{REQUEST_URI}"/>
        </rule>

        <!-- All other URLs are mapped to the node.js site entry point -->
        <rule name="DynamicContent">
          <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="True"/>
          </conditions>
          <action type="Rewrite" url="server.js"/>
        </rule>
      </rules>
    </rewrite>

    <!-- 'bin' directory has no special meaning in node.js and apps can be placed in it -->
    <security>
      <requestFiltering>
        <hiddenSegments>
          <remove segment="bin"/>
        </hiddenSegments>
      </requestFiltering>
    </security>

    <!-- Make sure error responses are left untouched -->
    <httpErrors existingResponse="PassThrough" />

    <!--
      You can control how Node is hosted within IIS using the following options:
        * watchedFiles: semi-colon separated list of files that will be watched for changes to restart the server
        * node_env: will be propagated to node as NODE_ENV environment variable
        * debuggingEnabled - controls whether the built-in debugger is enabled
      See https://github.com/tjanczuk/iisnode/blob/master/src/samples/configuration/web.config for a full list of options
    -->
    <!--<iisnode watchedFiles="web.config;*.js"/>-->
  </system.webServer>
</configuration> 

После того, как вы добавили и внесли изменения в свои маршруты в зависимости откак вам нужно, путем настройки файла server.js.

Нажмите на Azure, и ваше приложение начнет работать, так как Azure теперь запустит узел server.js и будет знать, где его найти.Кроме того, файл web.config перезапишет URL, поэтому вам не нужно добавлять yoururl.azure.net:3000, вы можете просто ввести URL, и он будет работать.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...