我试图用两个容器组成docker应用:
Mongo容器工作正常,而应用程序无法连接到mongo。 node.js应用程序和mongostat都不能。奇怪的是,我尝试在装有Win10的两台计算机上运行该项目,并且在另一台计算机上正常运行。
当我从应用容器运行package mj.eps.action;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.Vector;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.mj.eps.dto.business.auction.UploadObject;
import com.mj.eps.dto.training.IndexValueReportObject;
import com.mj.eps.framework.util.FileScaner;
import com.mj.eps.framework.util.IConstant;
public class IndexValueAction extends EPSBaseAction{
public IndexValueAction() {
super();
}
@SuppressWarnings("unchecked")
@Override
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
Vector<String> vector = new Vector<String>();
ActionErrors errors = new ActionErrors();
ActionForward forward = new ActionForward();
try{
String contentType = request.getContentType();
if ((contentType != null)
&& (contentType.indexOf("multipart/form-data") >= 0)) {
DataInputStream in =
new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();
byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
while (totalBytesRead < formDataLength) {
byteRead =
in.read(dataBytes, totalBytesRead, formDataLength);
totalBytesRead += byteRead;
}
String file = new String(dataBytes);
try {
String saveFile = file.substring(file.indexOf("filename=\"") + 10);
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1, saveFile.indexOf("\""));
int lastIndex = contentType.lastIndexOf("=");
String boundary =
contentType.substring(
lastIndex + 1,
contentType.length());
int pos;
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
int boundaryLocation = file.indexOf(boundary, pos) - 4;
int startPos = ((file.substring(0, pos)).getBytes()).length;
int endPos =
(
(file.substring(0, boundaryLocation))
.getBytes())
.length;
Vector<IndexValueReportObject> indexObjectVector = new Vector<IndexValueReportObject>();
Date dt = new Date();
SimpleDateFormat df = new SimpleDateFormat();
df.applyPattern("dd-MM-yy hh-mm-ss");
saveFile = saveFile.substring(0, saveFile.indexOf("."))+ "-"+ df.format(dt)+ ".xls";
String uploadFilePath = "";
ServletContext sc1 = request.getSession().getServletContext();
Properties properties = new Properties();
String realPath1 = sc1.getRealPath("serverPath.properties");
FileInputStream fis = new FileInputStream(realPath1);
properties.load(fis);
uploadFilePath = properties.getProperty("fileUpload.path");
FileOutputStream fileOut = new FileOutputStream(uploadFilePath + saveFile);
System.out.println(uploadFilePath);
if(endPos > dataBytes.length )
endPos = dataBytes.length;
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();
Vector<String[]> rowVector = new Vector<String[]>();
Vector<Object> errorVector = new Vector<Object>();
UploadObject uploadObject = new UploadObject();
int errorId=0;
try {
File outFile = new File(uploadFilePath + saveFile);
ServletConfig config = getServlet();
ServletContext sc = config.getServletContext();
boolean retVal = false;
boolean exists = true;
String filepath = outFile.getAbsolutePath();
String realPath = sc.getRealPath("virusCheck.properties");
exists = FileScaner.loadProperty(realPath);
if (exists) {
retVal = FileScaner.checkVirus(realPath, filepath);
if (!retVal) {
FileScaner.cleanFile(filepath);
errors.add(
ActionErrors.GLOBAL_ERROR,
new ActionError(
"errors.dynamic",
"<li>Virus found!!"));
}
if (retVal) {
retVal = FileScaner.checkFileSign(filepath);
if (!retVal) {
FileScaner.cleanFile(filepath);
errors.add(
ActionErrors.GLOBAL_ERROR,
new ActionError(
"errors.dynamic",
"<li>File type not supported!!"));
}
}
}
else {
}
if (retVal) {
}
if (errors.isEmpty())
{
***FileInputStream inputStream=new FileInputStream(uploadFilePath + saveFile);
Workbook w = Workbook.getWorkbook(inputStream);
Sheet read_sheet = w.getSheet(0);***
int rows=read_sheet.getRows();
for (int j=1;j<rows;j++){
String[] fields=new String[4];
for(int i=0;i<fields.length;i++)
{
Cell cell=read_sheet.getCell(i,j);
fields[i]=cell.getContents().trim();
if(fields[0] != null ){
try{
if (fields[i].indexOf(".") > 0) {
if (i != 1) {
fields[i] = fields[i];
}else {
fields[i].substring(0, fields[i].indexOf("."));
}
}
}
catch(Exception e1)
{
int k=i+1;
errorVector.add("Invalid data at field "+k);
System.out.println(" err1 :" + e1.toString());
errorId = 1;
}
}
}
if(!(fields[0] == null || (fields[0].trim().equals(""))))
{
rowVector.add(fields);
}
else{
break;
}
}
uploadObject.setErrorId(errorId);
uploadObject.setErrorVector(errorVector);
uploadObject.setRowVector(rowVector);
errorId = uploadObject.getErrorId();
rowVector = uploadObject.getRowVector();
errorVector = uploadObject.getErrorVector();
if (errorId == 0) {
int row = 0;
if (rowVector.size() > 0) {
for (int i = 0; i < rowVector.size(); i++) {
IndexValueReportObject indexValueReportObj =
new IndexValueReportObject();
String[] fields =
rowVector.elementAt(i);
System.out.println("abc>>>>>"+fields[0]);
System.out.println("abc>>>>>>>>>>>>>"+fields[1]);
System.out.println("abc>>>>>>>>>>>>>>>>>"+fields[2]);
System.out.println("abc>>>>>>>>>>>>>>>>>>>>>>>"+fields[3]);
try{
indexValueReportObj
.setDate(
Timestamp.valueOf(fields[0]));
}catch (Exception e1)
{
row = i + 1;
vector.add("Invalid Date at row " + (row+1));
}
try{
indexValueReportObj
.setPlatts(
new BigDecimal(fields[1]));
}catch (Exception e1)
{
row = i + 1;
vector.add("Invalid Platts Value at row " + (row+1));
}
try{
indexValueReportObj
.setArgus(
new BigDecimal(fields[2]));
}catch (Exception e1)
{
row = i + 1;
vector.add("Invalid Argus Value at row " + (row+1));
}
try{
indexValueReportObj
.setTsi(
new BigDecimal(fields[3]));
}catch (Exception e1)
{
row = i + 1;
vector.add("Invalid TSI value at row " + (row+1));
}
indexObjectVector.add(
indexValueReportObj);
}
} else {
vector.add(
"No Bidder is created in the excel file ");
}
} else {
for (int k = 0; k < errorVector.size(); k++) {
String errorDescription =
(String) errorVector.get(k);
vector.add(errorDescription);
}
}
}
} catch (Exception e1) {
errorId = uploadObject.getErrorId();
rowVector = uploadObject.getRowVector();
errorVector = uploadObject.getErrorVector();
for (int k = 0; k < errorVector.size(); k++) {
String errorDescription =
(String) errorVector.get(k);
vector.add(errorDescription);
}
}
String filePathAndName=uploadFilePath + saveFile;
System.out.println("indexObjectVector"+indexObjectVector);
request.setAttribute(
IConstant.INDEX_OBJECT_VECTOR,
indexObjectVector);
request.getSession().setAttribute(
IConstant.FILE_NAME,
filePathAndName);
request.setAttribute(IConstant.UPLOAD_MESSAGE, "uploaded");
} catch (Exception e1) {
vector.add("File name or sheet name error ");
}
} else {
vector.add("File Type mismatch ");
}
} catch (Exception e) {
vector.add("No excel has been selected ");
}
if (!errors.isEmpty()) {
request.setAttribute(IConstant.ERROR_VECTOR, errors);
forward = mapping.findForward("failureUpload");
} else {
forward = mapping.findForward("success");
}
return forward;
}
}
或user
-----
user_id
name
...
Workout
-----
workout_id
name
....
Exercise
------
exercise_id
name
....
workout_exercise
----------
workout_id
exercise_id
sequence -- this is how you capture the sequence of exercises within a workout
... -- there may be other attributes, e.g. number of repetitions, minimum duration, recommended rest period
user_workout
--------
user_id
workout_id
.... -- there may be other attributes, e.g. "active", "start date", "rating"
时,这些是mongo容器中的日志:
node app.js
这意味着两个容器都可以互相看到,因此.yml文件应该可以。如果问题出在代码上,那么它就不能同时在两台计算机上工作。
Dockerfile:
mongostat --uri "mongodb://mongo:27017/project"
docker-compose.yml:
2019-05-22T09:33:52.225+0000 I NETWORK [conn17] received client metadata from 192.168.96.2:42916 conn17: { driver: { name: "nodejs", version: "3.1.10" }, os: { type: "Linux", name: "linux", architecture: "x64", version: "4.9.125-linuxkit" }, platform: "Node.js v10.15.3, LE, mongodb-core: 3.1.9" }
2019-05-22T09:33:52.231+0000 I NETWORK [conn17] end connection 192.168.96.2:42916 (0 connections now open)
来自app.js的代码段:
FROM node:10.15.3-alpine
RUN apk update && apk --no-cache --virtual build-dependencies add python make g++ && apk del build-dependencies
RUN mkdir -p /home/node/app && chown -R node:node /home/node/app
WORKDIR /home/node/app
COPY package*.json ./
USER node
COPY --chown=node:node . .
ENV NPM_CONFIG_PREFIX=/home/node/.npm-global
RUN npm install
EXPOSE 3000
CMD ["node", "app.js"]
答案 0 :(得分:1)
如果在连接到mongo数据库之前在应用程序中插入“ sleep 10”是否有帮助?如果是这样,添加类似wiatforit(https://github.com/maxcnunes/waitforit)之类的方法可能会有所帮助。
答案 1 :(得分:1)
由于遇到getaddrinfo ENOTFOUND
错误,因此mongo
主机名无法解析。通常,发生这种情况的原因有两个:1)您的容器不在同一网络上,或者2)另一个容器尚未启动并运行。看到它们在同一个网络上,这听起来像是容器处于启动状态。
要进行故障排除,我将启动另一个容器,将其放在网络上,并验证mongo
主机名解析。
docker container run --rm -ti --network mongo ubuntu
$ apt update && apt install -y dnsutils
$ dig mongo
这时,您应该看到A
记录解析到数据库。如果没有,请验证mongo数据库容器是否已启动并正在运行。
您也可以尝试在您的应用容器中执行此操作。如果可以,请使用waitforit
之类的方法。这是一个常见问题,因为应用程序可能在数据库运行或准备接受连接之前启动。
作为另一项反馈,您无需公开mongo端口。这使世界可以访问它,这很可能不是您想要的。您仍然可以在不暴露端口的情况下进行容器到容器的通信。
答案 2 :(得分:0)
经过数小时的尝试,我找到了解决方案:关闭Windows防火墙。而已。
感谢您的帮助。